forked from avani112/HacktoberFest2021-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
quickSort.c
57 lines (57 loc) · 1.32 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
#include<stdio.h>
int swap = 0;
void printArray(int A[], int n){
printf("Array:");
for(int i=0; i<n; i++){
printf("%d ", A[i]);
}
printf("\n");
}
int partition(int A[], int low, int high){
int pivot = A[low];
int temp;
int i = low+1;
int j = high;
do{
while(A[i]<=pivot){
i++;
}
while (A[j]>pivot){
j--;
}
if(i<j){
temp = A[i];
A[i] = A[j];
A[j] = temp;
swap++;
}
// printArray(A, 6);
}while(i<j);
//swap A[low] and A[j]
temp = A[low];
A[low] = A[j];
A[j] = temp;
swap++;
return j;
}
void quickSort(int A[], int low, int high){
int partitionIndex; //index of pivot after partition
if(low<high){
partitionIndex = partition(A, low, high);
// printf("partition index: %d", A[partitionIndex]);
quickSort(A, low, partitionIndex-1); //sort left subarray
quickSort(A, partitionIndex+1, high); //sort right subarray
}
}
int main(){
int n;
scanf("%d", &n);
int b[n];
for(int i=0; i<n; i++)
scanf("%d", &b[i]);
int B[] = {1, 2, 3, 4, 5, 6};
quickSort(b, 0, 5);
printArray(b, 6);
printf("Swaps:%d", swap);
return 0;
}