-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquick_sort.c
67 lines (58 loc) · 1.42 KB
/
quick_sort.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
#include<stdio.h>
#include<conio.h>
void swap(int* a,int* b);
void quick_sort(int *a,int low,int high);
int partition(int *array,int low,int high);
void print(int *a,int n);
// main function
void main(){
int array[100];
int n;
printf("How many number is you want to enter:");
scanf("%d",&n);
printf("\n Enter value");
for(int i=0;i<n;i++){
scanf("%d",&array[i]);
}
printf("applying sorting algorithm...\n");
quick_sort(array,0,n);
print(array,n);
printf("\n Array is sorted ");
}
// swaping function
void swap(int*a,int*b){
int temp;
temp=*a;
*a=*b;
*b=temp;
}
// print function
void print(int*a,int n){
printf("\n");
for(int i=0;i<n;i++){
printf("%d\t",a[i]);
}
}
// sorting algorithm
int partition(int *array, int low,int high){
int j;
int pivot=array[high];// selecting right most element
int i=low-1;// Index of smaller element
for( j=low;j<high;j++){
if(array[j]<pivot){
// increment index of smaller element
i++;
swap(&array[i],&array[j]);
}
}
swap(&array[j+1],&array[high]);
return (i+1);
}
void quick_sort(int array,int low,int high){
int pivot_index;
if(low<high){
pivot_index=partition(array,low,high);
quick_sort(array,low,pivot_index-1);
quick_sort(array,pivot_index+1,high);
}
}