-
Notifications
You must be signed in to change notification settings - Fork 0
/
QuickSort.c
62 lines (51 loc) · 1.19 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
#include <stdio.h>
void quicksort(int *, int, int);
int partition(int *arr, int start, int end);
void display(int* arr, int len);
int main(void)
{
int array[] = {5, 3, 8, 9, 4, 6};
display(array, 6);
quicksort(array, 0, 5);
display(array, 6);
return 0;
}
void quicksort(int *arr, int start, int end)
{
if(start < end){
int pivotPosition = partition(arr, start, end);
quicksort(arr, start, pivotPosition-1);
quicksort(arr, pivotPosition + 1, end);
}
}
int partition(int *arr, int start, int end)
{
int pivotPos = end;
int pivotVal = arr[pivotPos];
int i = start;
int j = end - 1;
while(i < j){
while(arr[i] < pivotVal && i < end)
i++;
while(arr[j] > pivotVal && j > start)
j--;
swap(arr, i, j);
}
swap(arr, i, j);
if(arr[i] > arr[pivotPos])
swap(arr, i, pivotPos);
return i;
}
void swap(int *arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
void display(int* arr, int len)
{
printf("\nThe elements of the array are : ");
for(int i = 0; i < len; i++){
printf("%d ",arr[i]);
}
}