-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquick-sort.c
More file actions
46 lines (40 loc) · 880 Bytes
/
Copy pathquick-sort.c
File metadata and controls
46 lines (40 loc) · 880 Bytes
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
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int arr[], int lo, int hi) {
int pivot = arr[lo];
int i = lo + 1;
int j = hi;
while (i <= j) {
while (i <= hi && arr[i] <= pivot) {
i++;
}
while (j > lo && arr[j] >= pivot) {
j--;
}
if (i < j) {
swap(&arr[i], &arr[j]);
}
}
swap(&arr[lo], &arr[j]);
return j;
}
void quick_sort(int arr[], int lo, int hi) {
if(lo < hi) {
int j = partition(arr, lo, hi);
quick_sort(arr, lo, j-1);
quick_sort(arr, j+1, hi);
}
}
int main() {
int arr[] = {2, 4, 1, 1, 0, 5};
int n = sizeof(arr) / sizeof(arr[0]);
quick_sort(arr, 0, n - 1);
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}