forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
QuickSort.c
87 lines (74 loc) · 2.02 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
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
82
83
84
85
86
87
#include <stdio.h>
#include <stdbool.h>
void print_array(int array[], int size) {
printf("[ ");
for (int index = 0; index < size; ++index) {
printf("%d", array[index]);
if (index < size - 1) {
printf(", ");
}
}
printf(" ]\n");
}
void swap(int array[], int src_index, int dest_index) {
int temp = array[src_index];
array[src_index] = array[dest_index];
array[dest_index] = temp;
}
int lomuto_partition(int array[], int low, int high) {
int pivot = array[high];
int index = low;
for (int j = low; j < high; ++j) {
if (array[j] < pivot) {
swap(array, index, j);
++index;
}
}
swap(array, index, high);
return index;
}
void quicksort_lomuto(int array[], int low, int high) {
if (low < high) {
int pivot = lomuto_partition(array, low, high);
quicksort_lomuto(array, low, pivot - 1);
quicksort_lomuto(array, pivot + 1, high);
}
}
int hoare_partition(int array[], int low, int high) {
int pivot = array[low];
int i = low - 1;
int j = high + 1;
while (true) {
do {
++i;
} while (array[i] < pivot);
do {
--j;
} while (array[j] > pivot);
if (i >= j) {
return j;
}
swap(array, i, j);
}
}
void quicksort_hoare(int array[], int low, int high) {
if (low < high) {
int pivot = hoare_partition(array, low, high);
quicksort_hoare(array, low, pivot);
quicksort_hoare(array, pivot + 1, high);
}
}
int main() {
int example_lomuto[] = {5, 3, 1, 4, 2};
int example_hoare[] = {5, 3, 1, 4, 2};
int size = 5;
printf("lomuto quicksort partition:\n");
print_array(example_lomuto, size);
quicksort_lomuto(example_lomuto, 0, size - 1);
print_array(example_lomuto, size);
printf("hoare quicksort partition:\n");
print_array(example_hoare, size);
quicksort_hoare(example_hoare, 0, size - 1);
print_array(example_hoare, size);
return 0;
}