For me, your code crashes with much larger sizes (about 370,000 elements). You probably ran into a platform limit (possibly limited by recursion depth due to). Without an accurate error message, it is of course difficult to be sure.
Your input set is most likely a pathological case for your implementation - see What makes a bad case for quick sorting?
- , , . - :
int v0 = a[lo], v1 = a[(lo+hi+1)/2], v2 = a[hi];
int v = v0 < v1 ? v1 < v2 ? v1 : v0 < v2 ? v2 : v0 : v0 < v2 ? v0 : v1 < v2 ? v2 : v1;
. , , , . - :
void quicksort(int a[], int lo, int hi) {
while (lo < hi) {
int j = partition(a, lo, hi);
if (j - lo < hi -j) {
quicksort(a, lo, j-1);
lo = j+1;
} else {
quicksort(a, j+1, hi);
hi = j-1;
}
}
}
( - . - , 17 ).
, , . .
P.S. main():
calloc() - , , malloc() , :
int *arr = malloc(len * sizeof *arr);
if (!arr) return fprintf(stderr, "allocation failed\n"), EXIT_FAILURE;
, :
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int partition(int *a, int i, int j) {
int v0 = a[i], v1 = a[(i+j+1)/2], v2 = a[j];
int v = v0 < v1 ? v1 < v2 ? v1 : v0 < v2 ? v2 : v0 : v0 < v2 ? v0 : v1 < v2 ? v2 : v1;
while (i < j) {
while (a[i] < v && ++i < j)
;
while (v < a[j] && i < --j)
;
int t = a[j]; a[j] = a[i]; a[i]= t;
}
a[i] = v;
return j;
}
void quicksort(int a[], int lo, int hi) {
while (lo < hi) {
int j = partition(a, lo, hi);
if (j - lo < hi -j) {
quicksort(a, lo, j-1);
lo = j+1;
} else {
quicksort(a, j+1, hi);
hi = j-1;
}
}
}
int main() {
int len = INT_MAX/2+1;
printf("New Arr with len = %d\n",len);
int *arr = malloc(len * sizeof *arr);
if (!arr) return fprintf(stderr, "allocation failed\n"), EXIT_FAILURE;
for (int j = 0; j < len; ++j) {
arr[j] = len-j;
}
printf("start sorting\n");
quicksort(arr, 0, len-1);
for (int i = 0; i+1 < len; ++i)
if (arr[i] >= arr[i+1])
return fprintf(stderr, "not sorted\n"), EXIT_FAILURE;
free(arr);
}