-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquicksort.c
49 lines (44 loc) · 1.07 KB
/
quicksort.c
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
#include <stdio.h>
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
int partition(int array[], int low, int high) {
int i, j;
int pivot = array[high];
for (i = 0; i <= high && array[i] <= pivot; i++);
for (j = i; j < high; j++) {
if (array[j] <= pivot) {
swap(&array[i], &array[j]);
i++;
}
}
swap(&array[i], &array[j]);
return i;
}
int alternate_partition(int array[], int low, int high) {
int i, j;
int pivot = array[high];
for (i = low - 1, j = low; j <= high; j++) {
if (array[j] <= pivot) {
i++;
swap(&array[i], &array[j]);
}
}
return i;
}
void quicksort(int array[], int low, int high) {
if (low < high) {
int mid = alternate_partition(array, low, high);
quicksort(array, low, mid - 1);
quicksort(array, mid + 1, high);
}
}
int main() {
int array[] = {26, 38, 65, 97, 76, 13, 27};
quicksort(array, 0, 6);
for (int i = 0; i < 7; i++)
printf("%d ", array[i]);
return 0;
}