What is the problem? Why is there always a fixed value of comparisons and swaps? And am I correct in counting swaps and comparisons in principle? I mean, do I accidentally count them in the wrong places? Maybe in some places it is not necessary to do this? Please help me because I really can't figure out what's wrong
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void mergeAbstract(int *a, int lb, int split, int ub, int *count, int *swaps)
{
int size = ub - lb + 1;
int *sub = (int *)malloc((ub + 1) * sizeof(int));
int i = 0, j = size - 1, k = lb;
int s;
for (s = 0; s < split + 1 - lb; s++) sub[s] = a[lb + s];
for (s = split + 1 - lb; s < size; s++) sub[s] = a[ub - (s - (split + 1 -lb))];
while (i <= j) {
(*count) += 2;
if (sub[i] > sub[j]) {
(*swaps)++;
a[k] = sub[j];
j--;
} else {
(*swaps)++;
a[k] = sub[i];
i++;
}
k++;
}
(*count)++;
free(sub);
}
void mergeSort(int *a, int lb, int ub, int *count, int *swaps) {
long split;
if (lb < ub) {
split = (lb + ub) / 2;
mergeSort(a, lb, split, count, swaps);
mergeSort(a, split + 1, ub, count, swaps);
mergeAbstract(a, lb, split, ub, count, swaps);
}
}
void arrprint(int *arr, int n) {
printf("%d", *arr);
int i;
for (i = 1; i < n; i++) printf(" %d", arr[i]);
puts("");
}
int main(int argc, char *argv[]) {
int n = 10;
int *arr = NULL;
arr = (int *)malloc(n * sizeof *arr);
int c = 0;
int *count = &c;
int h = 0;
int *swaps = &h;
srand(time(NULL));
int s;
for (s = 0; s < n; s++)
arr[s] = rand() % 50;
arrprint(arr, n);
mergeSort(arr, 0, n - 1, count, swaps);
arrprint(arr, n);
free(arr);
puts("");
printf("Comparison ans swaps : %d %d\n", *count ,*swaps);
return 0;
}
Related
I made program that measure time of sorting n data arrays of int. Unfortunately my quicksort in worst case around 30000 numbers in array crashing program with return value 3221225725. For average case it works fine even for 500000 numbers (that is my max for testing).
Here is code for quicksort:
int part(int *tab, int left, int n)
{
int first = tab[left], i = left, j = n;
while (0 != 1)
{
while (tab[j] > first)
{
j--;
}
while (tab[i] < first)
{
i++;
}
if (i < j)
{
swap(&tab[i], &tab[j]);
i++;
j--;
}
else
return j;
}
}
void quick_sort(int *tab, int left, int n)
{
int pivot;
if (left < n)
{
pivot = part(tab, left, n);
quick_sort(tab, left, pivot);
quick_sort(tab, pivot + 1, n);
}
}
And here is code in for loop for data cases:
#include <stdio.h>
#include <stdlib.h>
#include "algorytmy.h"
#include <time.h>
int main(int argc, char *argv[]) {
srand(time(NULL));
int n;
clock_t czas1, czas2, czas3;
FILE *fw;
if (!(fw = fopen("danedowykresu_odwrotnie_zestaw2cd.txt", "w")))
{
printf("Blad otwarcia zbioru\n");
exit(2);
}
fprintf(fw,"Liczba danych;quicksort;shellsort;heapsort\n");
printf("Liczba danych;quicksort;shellsort;heapsort\n");
for(n = 25000; n < 500000; n += 1000)
{
int tab[n], i;
int *ptr = (int *)malloc(n * sizeof(int));
for (i = 0; i < n; i++)
ptr[i] = n - i;
czas1 = clock();
quick_sort(ptr, 0, n);
czas1 = clock() - czas1;
free(ptr);
for (i = 0; i < n; i++)
tab[i] = n - i;
czas2 = clock();
shell_sort(tab, n);
czas2 = clock() - czas2;
for (i = 0; i < n; i++)
tab[i] = n - i;
czas3 = clock();
heap_sort(tab, n);
czas3 = clock() - czas3;
fprintf(fw,"%d;%f;%f;%f\n", n, ((float)czas1) / CLOCKS_PER_SEC, ((float)czas2) / CLOCKS_PER_SEC, ((float)czas3) / CLOCKS_PER_SEC);
printf("%d;%f;%f;%f\n", n, ((float)czas1)/CLOCKS_PER_SEC, ((float)czas2) / CLOCKS_PER_SEC, ((float)czas3) / CLOCKS_PER_SEC);
}
fclose(fw);
return 0;
}
console screen
Your implementation is incorrect: it is unclear what you are testing with if (pocz < n). A pure implementation would test if (n - left > 1). The part() function has problems too: i and j are not properly initialized. It is always a good idea to verify correctness before even trying to measure performance.
The problem with quicksort worst case is you recurse too deep and eventually encounter a stack overflow.
Here is a modified version using a simple way to prevent deep recursion: only recurse on the smaller half and iterate on the larger one:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "algorytmy.h"
void swap(int *a, int *b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
int part(int *tab, int left, int n) {
int pivot = tab[left];
int i = left;
int j = n - 1;
for (;;) {
while (tab[i] < pivot)
i++;
while (tab[j] > pivot)
j--;
if (i < j) {
swap(&tab[i], &tab[j]);
i++;
j--;
} else {
return j + 1;
}
}
}
void quick_sort(int *tab, int left, int n) {
while (left + 1 < n) {
int p = part(tab, left, n);
if (p - left < n - p) {
quick_sort(tab, left, p);
left = p;
} else {
quick_sort(tab, p, n);
n = p;
}
}
}
int check_sorted(const int *ptr, int n, const char *name) {
for (int i = 1; i < n; i++) {
if (ptr[i - 1] > ptr[i]) {
printf("%s failed: ptr[%d] = %d > ptr[%d] = %d\n",
name, i - 1, ptr[i - 1], i, ptr[i]);
return 1;
}
}
return 0;
}
int main(int argc, char *argv[]) {
double czas1, czas2, czas3;
FILE *fw;
srand(time(NULL));
if (!(fw = fopen("danedowykresu_odwrotnie_zestaw2cd.txt", "w"))) {
printf("Blad otwarcia zbioru\n");
exit(2);
}
fprintf(fw,"Liczba danych;quicksort;shellsort;heapsort\n");
printf("Liczba danych;quicksort;shellsort;heapsort\n");
for (int n = 25000; n < 500000; n += 1000) {
int *ptr = malloc(n * sizeof(*ptr));
for (int i = 0; i < n; i++)
ptr[i] = n - i;
czas1 = clock();
quick_sort(ptr, 0, n);
czas1 = clock() - czas1;
check_sorted(ptr, n, "check_sorted");
for (int i = 0; i < n; i++)
ptr[i] = n - i;
czas2 = clock();
shell_sort(ptr, n);
czas2 = clock() - czas2;
check_sorted(ptr, n, "shell_sorted");
for (int i = 0; i < n; i++)
ptr[i] = n - i;
czas3 = clock();
heap_sort(ptr, n);
czas3 = clock() - czas3;
check_sorted(ptr, n, "heap_sorted");
fprintf(fw,"%d;%f;%f;%f\n",
n, czas1 / CLOCKS_PER_SEC, czas2 / CLOCKS_PER_SEC, czas3 / CLOCKS_PER_SEC);
printf("%d;%f;%f;%f\n",
n, czas1 / CLOCKS_PER_SEC, czas2 / CLOCKS_PER_SEC, czas3 / CLOCKS_PER_SEC);
free(ptr);
}
fclose(fw);
return 0;
}
The sorting seems to be working correctly. At least it sorts correctly :) It remains only to count the number of comparisons and swaps. How to calculate and output it?Somehow stalled at this point.. I will be very grateful for your help.If you demonstrate it with the updated code , I will be doubly grateful.
#include <stdio.h>
#include <stdlib.h>
void keyDown(int* arr, int n, int head)
{
int j;
if(2*head + 2 < n && arr[2*head + 1] < arr[2*head + 2])
{
j = 2*head + 2;
}
else j = 2*head + 1;
while(arr[head] < arr[j] && head < n / 2)
{
int tmp = arr[head];
arr[head] = arr[j];
arr[j] = tmp;
head = j;
if(2*head + 2 < n && arr[2*head + 1] < arr[2*head + 2])
{
j = 2*head + 2;
}
else j = 2*head + 1;
}
}
void heapSort(int* arr, int n)
{
int i;
for(i = n/2 - 1; i >= 0; i--)
{
keyDown(arr,n,i);
}
int l = n;
while(l > 1)
{
l--;
int tmp = arr[l];
arr[l] = arr[0];
arr[0] = tmp;
keyDown(arr,l,0);
}
}
int main(int argc, char *argv[]) {
int n=10;
int start, end,i;
int *arr;
arr=(int *)malloc(n*sizeof(int));
time_t invocation_time = time(NULL);
srand(invocation_time);
int s;
for (s=0;s<n;s++)
{
arr[s] = rand() % 50;
printf ("%d \n", arr[s]);
}
printf ("\n");
heapSort(arr, n);
for (i=0;i<n;i++){
printf ("%d \n", arr[i]);
}
return 0;
}
count the number of comparisons and swaps
make functions
//global counters
unsigned comparisons = 0, swaps = 0;
int lessthan(int a, int b) {
comparisons++;
return (a < b);
}
void swap(int *a, int *b) {
swaps++;
int tmp = *a; *a = *b; *b = tmp;
}
and then replace comparisons and swaps in your existing code with the specific function you need.
int main(int argc, char **argc) {
//...
if (lessthan(a[i], a[j])) swap(a+i, a+j);
//...
printf("comparisons: %u; swaps: %u\n", comparisons, swaps);
}
I'm trying to make a merge sort algorithm in C. The problem is that it does not work for a big number of elements. If the array has 100000 elements it's OK but if it has 1e6 or 1e7 then it crashes. I thought that you cannot give such a big number of elements for an array but after I have read that this is not true, you should be able to give 1e7 elements. After that I thought that maybe int range is to small but that's not the case, int goes to 1e9. I don't really know what's the problem and why it doesn't work, so please help. Thanks in advance!
#include <stdio.h>
#include <stdlib.h>
int n;
void merge(int *, int, int);
void mergeSort(int *, int, int);
void bubbleSort(int *, int);
int main() {
// scanf("%d",&n);
n = 10000000;
int *a = (int *)malloc(n * sizeof(int));
if (a == NULL) {
printf("Nu s-a putut aloca memorie.");
exit(0);
}
for (int i = 0; i < n; i++)
a[i] = rand() % 50;
mergeSort(a, 0, n - 1);
//bubbleSort(a, n - 1);
// for (int i = 0; i < n; i++) {
// printf("%d ", a[i]);
// }
free(a);
return 0;
}
void merge(int *a, int start, int sfarsit) {
int mij = (start + sfarsit) / 2;
int i = start;
int j = mij + 1;
int k = start;
int aux[10000000];
while (i <= mij && j <= sfarsit) {
if (a[i] < a[j])
aux[k++] = a[i++];
else
aux[k++] = a[j++];
}
while (i <= mij)
aux[k++] = a[i++];
while (j <= sfarsit)
aux[k++] = a[j++];
for (int i = start; i <= sfarsit; i++)
a[i] = aux[i];
}
void mergeSort(int *a, int start, int sfarsit) {
if (start >= sfarsit)
return ;
int mij = (start + sfarsit) / 2;
mergeSort(a, start, mij);
mergeSort(a, mij + 1, sfarsit);
merge(a, start, sfarsit);
}
This:
int aux[10000000];
is problem. That will be to much for the stack to handle. Change to this:
int *aux = malloc(sizeof(*aux) * 10000000);
Of course, you need to use free(aux) in the end of the function merge and also check if the allocation was successful.
Also, you should of course allocate in relation to sfarsit but judging from your other code, it does not seem like I need to tell you that.
Your program has this problem: the definition int aux[10000000]; in the merge function defines a temporary array with automatic storage (aka on the stack) which is:
very large, potentially too large for your system, causing a stack overflow.
not necessary large enough if the array to be sorted is larger than 10 million elements.
You should allocate this temporary array, either locally in merge or in a wrapper function that would call mergesort with an extra argument.
It is also unnecessary and quite error prone to make n a global variable.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
int mergeSort(int *a, int length);
void bubbleSort(int *, int);
int main() {
int n;
int *a;
n = 10000000;
//scanf("%d", &n);
if ((a = malloc(sizeof(*a) * n)) == NULL) {
printf("Nu s-a putut aloca memorie.");
return 1;
}
for (int i = 0; i < n; i++)
a[i] = rand() % 50;
mergeSort(a, n);
//bubbleSort(a, n);
for (int i = 1; i < n; i++) {
if (a[i] < a[i - 1]) {
printf("mergeSort failed\n");
break;
}
}
free(a);
return 0;
}
void merge(int *a, int start, int mij, int sfarsit, int *aux) {
int i = start;
int j = mij + 1;
int k = start;
while (i <= mij && j <= sfarsit) {
if (a[i] <= a[j])
aux[k++] = a[i++];
else
aux[k++] = a[j++];
}
while (i <= mij)
aux[k++] = a[i++];
while (j <= sfarsit)
aux[k++] = a[j++];
for (i = start; i <= sfarsit; i++)
a[i] = aux[i];
}
void mergeSortAux(int *a, int start, int sfarsit, int *aux) {
if (start >= sfarsit)
return;
int mij = (start + sfarsit) / 2;
mergeSortAux(a, start, mij, aux);
mergeSortAux(a, mij + 1, sfarsit, aux);
merge(a, start, mij, sfarsit, aux);
}
int mergeSort(int *a, int length) {
if (length > 1) {
int *aux = malloc(sizeof(*aux) * length);
if (aux == NULL)
return -1;
mergeSortAux(a, 0, length - 1, aux);
free(aux);
}
return 0;
}
Note that you can improve this code:
using size_t instead of int for the array sizes and index variables
using the convention start included and stop excluded, which avoids the +1/-1 adjustments.
by not copying the remaining values from the right slice as they are already in place in the original array.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
int mergeSort(int *a, size_t length);
int main(int argc, char *argv[]) {
size_t n = 10000000;
int *a;
int res = 0;
if (argc > 1) {
n = strtoll(argv[1], NULL, 0);
}
if ((a = malloc(sizeof(*a) * n)) == NULL) {
printf("Nu s-a putut aloca memorie.");
return 1;
}
for (size_t i = 0; i < n; i++) {
a[i] = rand() % 50;
}
if (mergeSort(a, n)) {
printf("mergeSort failed: allocation error\n");
res = 1;
} else {
for (size_t i = 1; i < n; i++) {
if (a[i] < a[i - 1]) {
printf("mergeSort failed: out of order\n");
res = 1;
break;
}
}
}
free(a);
return res;
}
void merge(int *a, size_t start, size_t mid, size_t stop, int *aux) {
size_t i = start;
size_t j = mid;
size_t k = start;
while (i < mid && j < stop) {
if (a[i] <= a[j])
aux[k++] = a[i++];
else
aux[k++] = a[j++];
}
while (i < mid)
aux[k++] = a[i++];
for (i = start; i < k; i++)
a[i] = aux[i];
}
void mergeSortAux(int *a, size_t start, size_t stop, int *aux) {
if (stop - start >= 2) {
size_t mid = start + (stop - start) / 2;
mergeSortAux(a, start, mid, aux);
mergeSortAux(a, mid, stop, aux);
merge(a, start, mid, stop, aux);
}
}
int mergeSort(int *a, size_t length) {
if (length > 1) {
int *aux = malloc(sizeof(*aux) * length);
if (aux == NULL)
return -1;
mergeSortAux(a, 0, length, aux);
free(aux);
}
return 0;
}
Basically this is a C code for Oil Well challenge from hackerrank website (https://www.hackerrank.com/challenges/oil-well). I am getting segmentation fault or abort called when I submit this code.(It is working sometime in my system compiler).
Can someone tell me how to rectify this problem?. Thanks in advance.
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int *min, c, r, q = 0;
void findmin()
{
int i, minimum = min[0];
for (i = 0; i < q; i++)
{
if (min[i] > minimum)
minimum = min[i];
}
printf("%d", minimum);
}
void calculate(int a[], int r)
{
int sum = 0;
int i;
int *x, *y;
x = (int *) malloc(sizeof(int) * 3);
y = (int *) malloc(sizeof(int) * 3);
for (i = 0; i <= r; i++)
{
x[i] = a[i] % c;
y[i] = a[i] / c;
}
for (i = 1; i <= r; i++)
{
if ((x[i] - x[i - 1]) > (y[i] - y[i - 1]))
sum = sum + (x[i] - x[i - 1]);
else
sum = sum + (y[i] - y[i - 1]);
}
min[q] = sum;
q++;
free(x);
free(y);
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
void permute(int a[], int l, int r)
{
int i;
if (l == r)
{
for (i = 0; i <= r; i++)
calculate(a, r);
}
else
{
for (i = l; i <= r; i++)
{
swap((a + l), (a + i));
permute(a, l + 1, r);
swap((a + l), (a + i));
}
}
}
int main(void)
{
int i, j, k = 0;
scanf("%d%d", &r, &c);
int *arr;
arr = (int *) malloc(sizeof(int) * r * c);
int **x = (int **) malloc(r * sizeof(int *));
for (i = 0; i < r; i++)
x[i] = (int *) malloc(c * sizeof(int));
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
scanf("%d", &x[i][j]);
for (i = 0; i < r; i++)
{
for (j = 0; j < c; j++)
{
if (x[i][j] == 1)
{
arr[k] = c * i + j;
k++;
}
}
}
/*printf("Content of arr array is:\n");
for(i=0;i<k;i++)
printf("%d \n",arr[i]);
*/
min = (int *) malloc(sizeof(int) * r * c);
permute(arr, 0, k - 1);
findmin();
free(arr);
free(x);
free(min);
}
Updated code(With all the suggestions and answers taken into account )
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int *min,c,r,q=0;
void findmin()
{
int i,minimum=min[0];
/*printf("\nmin array is \n");
for(i=0;i<q;i++)
{
printf("%d ",min[i]);
}*/
for(i=0;i<q;i++)
{
if(min[i]<minimum)
minimum=min[i];
}
printf("%d",minimum);
}
void calculate(int a[],int r)
{
int sum=0;
int i;
int *x,*y;
x = (int *)malloc(sizeof(int)*r+1);
y = (int *)malloc(sizeof(int)*r+1);
for(i=0;i<=r;i++)
{
x[i]=a[i]%c;
y[i]=a[i]/c;
}
for(i=1;i<=r;i++)
{
if(abs(x[i]-x[i-1])>abs(y[i]-y[i-1]))
sum=sum+abs(x[i]-x[i-1]);
else
sum=sum+abs(y[i]-y[i-1]);
}
min[q]=sum;
q++;
free(x);
free(y);
//printf("I am here also");
}
void swap(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
void permute(int a[],int l,int r)
{
int i;
if(l==r)
{
for(i=0;i<=r;i++)
//printf("%d ",a[i]);
calculate(a,r);
//printf("\n");
}
else
{
for(i=l;i<=r;i++)
{
swap((a+l),(a+i));
permute(a,l+1,r);
swap((a+l),(a+i));
}
}
}
int main(){
int i,j,k=0;
scanf("%d%d",&r,&c);
int *arr;
arr = (int *)malloc(sizeof(int)*r*c);
int **x = (int **)malloc(r * sizeof(int *));
for (i=0; i<r; i++)
x[i] = (int *)malloc(c * sizeof(int));
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%d",&x[i][j]);
/*for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
printf("%d ",x[i][j]);
printf("\n");
}*/
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
if(x[i][j]==1)
{
arr[k]=c*i+j;
k++;
}
}
}
//printf("Content of arr array is:\n");
//for(i=0;i<k;i++)
//printf("%d \n",arr[i]);
//printf("\nCalling permutation\n");
min = (int *)malloc(sizeof(int)*r*c);
permute(arr,0,k-1);
//printf("\nFinding min call\n");
findmin();
free(arr);
for (i = 0; i < r; i++)
{
free(x[i]);
}
free(x);
free(min);
return 0;
}
Here do *(r+1) rather than *3
x = (int *)malloc(sizeof(int)*3);
y = (int *)malloc(sizeof(int)*3);
Change min[i] > minimum to min[i] < minimum
free all the memory you've allocated i.e. from x[0] to x[r] and y[0] to y[r].
Other than this you're probably all good.
You are allocating (r * sizeof (int)) + 1 bytes,
x = (int *)malloc(sizeof(int)*r+1);
y = (int *)malloc(sizeof(int)*r+1);
but your loop accesses r+1 int objects:
for(i=0;i<=r;i++)
{
x[i]=a[i]%c;
y[i]=a[i]/c;
}
Correct the behaviour based on whatever your intent is - I suspect you want to allocate (r + 1) * sizeof (int) bytes.
i've already sought information for the quick-sort algorithm. But i still can not realize it on C. I'm trying but the Quicksort function doesn't work at all. I Can't find errors in my code. Please, help me to understand what's going on.
#include <stdio.h>
#include <stdlib.h>
void swap(int a, int b)
{
int temp = 0;
temp = a;
a = b;
b = temp;
}
int Partition(int p , int r, int A[r - p + 1])
{
int j = 0;
int x = A[r - 1];
int i = p - 1;
for(j = p - 1; j < r - 1; j++) {
if(A[j] <= x) {
i = i + 1;
swap(A[i], A[j]);
}
}
swap(A[i], A[r - 1]);
return i + 1;
}
void Quicksort(int p, int r, int A[r - p + 1])
{
int q = 0;
if((p - 1) < (r - 1)) {
q = Partition(p ,r , A);
Quicksort(p, q - 1, A);
Quicksort(q + 1, r, A);
}
}
int main(int argc, char *argv[])
{
int A[] = {10, 5, 1, 3, 9, 2, 4, 8, 7, 6};
int i = 0;
int length = sizeof(A) / sizeof(int);
Quicksort(1, length , A);
for(i = 0; i < length; i ++) {
printf("%d ", A[i]);
}
printf("\n");
return 0;
}
You have to pass the values as pointers to the swap function
void swap(int *a, int *b)
{
int temp = 0;
temp = *a;
*a = *b;
*b = temp;
}
and then change
swap(A[i], A[j]);
to
swap(&A[i], &A[j]);
and
swap(A[i], A[r - 1]);
to
swap(&A[i], &A[r - 1]);