1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| #include <stdio.h>
void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; }
void printarr(int arr[], int n) { for (int i = 0; i < n; i++) { printf("%d,", arr[i]); } printf("\n"); }
int getpivot(int arr[], int left, int right) { if (right - left < 2) { return arr[left]; } int mid = (left + right) / 2; if (arr[left] > arr[mid]) { swap(&arr[left], &arr[mid]); } if (arr[left] > arr[right]) { swap(&arr[left], &arr[right]); } if (arr[mid] > arr[right]) { swap(&arr[mid], &arr[right]); } swap(&arr[mid], &arr[right - 1]); return arr[right - 1]; }
int partition(int arr[], int left, int right) { int pivot = getpivot(arr, left, right); int i = left; int j = right - 1; while (1) { while (arr[++i] < pivot) {} while (arr[--j] > pivot) {} if (i < j) { swap(&arr[i], &arr[j]); } else { break; } } printf("i = %d, j = %d, pivotval = %d\n", arr[i], arr[j], pivot); swap(&arr[i], &arr[right - 1]); return i; }
void quicksort(int arr[], int left, int right) { if (left + 3 < right) { int pivotidx = partition(arr, left, right); quicksort(arr, left, pivotidx - 1); quicksort(arr, pivotidx + 1, right); } else { for (int i = left + 1; i <= right; i++) { int temp = arr[i]; int j = i; for (; j > left && arr[j - 1] > temp; j--) { arr[j] = arr[j - 1]; } arr[j] = temp; } } }
int main() {
int arr[10] = {20, 38, 24, 23, 26, 32, 21, 29, 38, 28}; quicksort(arr, 0, 9); printarr(arr, 10); return 0; }
|