BUPT-homework/semester3/pset5/7-3-Quick-Sort.c
2022-11-13 21:17:24 +08:00

57 lines
920 B
C

#include <stdio.h>
#define N 10
#define CUTOFF 3
void print(int *arr) {
for (int i = 0; i < N; i++) {
printf("%d,", arr[i]);
}
}
void swap(int *arr, int l, int r) {
if (l != r) {
int tmp = arr[l];
arr[l] = arr[r];
arr[r] = tmp;
}
}
int partition(int *arr, int l, int r) {
// both edges included
int index = l;
int pivot = arr[l];
for (int i = l + 1; i <= r; i++) {
if (arr[i] < pivot) {
swap(arr, i, index);
index++;
}
}
swap(arr, index, l);
return index;
}
void quickSort(int *arr, int l, int r) {
int pi;
if (l < r) {
if (r - l < CUTOFF) {
printf("insert(%d,%d):", l, r - l + 1);
} else {
printf("Qsort(%d,%d):", l, r);
}
pi = partition(arr, l, r);
print(arr);
quickSort(arr, l, pi - 1);
quickSort(arr, pi + 1, r);
}
}
int main(void) {
int arr[] = {49, 38, 65, 97, 76, 13, 27, 50, 2, 8};
return 0;
}