-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuickSort.c
64 lines (51 loc) · 1.26 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
#include <stdio.h>
void swap(int a[], int idxA, int idxB)
{
int temp = a[idxA];
a[idxA] = a[idxB];
a[idxB] = temp;
}
int partitionOnPivot(int a[], int startIdx, int endIdx)
{
int pivotIdx = startIdx;
int pivotValue = a[endIdx];
for (int i = startIdx; i < endIdx; i++)
{
if (a[i] <= pivotValue)
{
swap(a, i, pivotIdx);
pivotIdx++;
}
}
// Move the pivot into proper position.
swap(a, pivotIdx, endIdx);
return pivotIdx;
}
void quickSort(int a[], int startIdx, int endIdx)
{
if (startIdx >= endIdx)
{
// All done!
return;
}
int pivotIdx = partitionOnPivot(a, startIdx, endIdx);
// Sort the values smaller than the pivot.
quickSort(a, startIdx, pivotIdx - 1);
// Sort the values larger than the pivot.
quickSort(a, pivotIdx + 1, endIdx);
}
int main()
{
int a[] = {5, 4, 2, 7, 1, 9, -3, 100, 4, 2, -5, 7};
int n = sizeof(a) / sizeof(int);
printf("Starting quick sort on array of size %u\n",n);
int startIdx = 0;
int endIdx = n-1;
quickSort(a, startIdx, endIdx);
printf("Sorted array:\n");
for(int i=0; i < n; i++)
{
printf("%d\n",a[i]);
}
return 0;
}