-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquick_sort.c
More file actions
65 lines (59 loc) · 1.39 KB
/
quick_sort.c
File metadata and controls
65 lines (59 loc) · 1.39 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int partition(int a[],int start,int end);
int randomize_partition(int a[],int start,int end);
void quick_sort(int a[],int start,int end);
void swap(int *a, int *b);
int main(){
int arr[100],n,i;
printf("Input the number of element : ");
scanf("%d",&n);
int start=0;
int end=n-1;
for(i=0;i<n;i++){
scanf("%d",&arr[i]);
}
quick_sort(arr,start,end);
printf("Array after sorting : ");
for(i=0;i<n;i++){
printf("%d ",arr[i]);
}
return 0;
}
void swap(int *a, int *b){ /// swaping function
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int partition(int a[],int start,int end){ /// pertition function
int pi,pivot,i,temp;
pi=start;
pivot=a[end];
for(i=start;i<end;i++){
if(a[i]<=pivot){
swap(&a[i],&a[pi]);
pi++;
}
}
swap(&a[end],&a[pi]);
return pi;
}
int randomize_partition(int a[],int start,int end){ /// randomized partition function
int pi,temp;
time_t t;
srand((unsigned) time(&t));
pi=start+(rand()%(end-start+1));
swap(&a[end],&a[pi]);
partition(a,start,end);
}
void quick_sort(int a[],int start,int end){ /// quick sort function
int pi;
if(start<end){
pi=randomize_partition(a,start,end);
quick_sort(a,start,pi-1);
quick_sort(a,pi+1,end);
}
return;
}