-
Notifications
You must be signed in to change notification settings - Fork 241
/
Copy pathQsort_recursive.c
55 lines (50 loc) · 896 Bytes
/
Qsort_recursive.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
#include<stdio.h>
int partition(int [], int, int);
void qsort(int [], int, int);
void swap(int *, int *);
void print(int [],int);
int main() {
int n;
printf("Enter the number of elements in the array : ");
scanf("%d",&n);
int a[n];
printf("Enter the array elements : ");
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
qsort(a,0,n-1);
print(a,n);
return 0;
}
void qsort(int a[], int l, int r ) {
int x;
if(l<r) {
x = partition(a,l,r);
qsort(a,l,x-1);
qsort(a,x+1,r);
}
}
int partition(int a[],int l, int r) {
int key = a[l];
int i=l+1,j=r;
while(i<j) {
while(a[i]<=key && i<r)
i++;
while(a[j]>key && j>l)
j--;
if(i<j)
swap(&a[i],&a[j]);
}
swap(&a[l],&a[j]);
return j;
}
void swap(int *p, int *q) {
int temp = *p;
*p=*q;
*q=temp;
}
void print(int a[], int n) {
printf("The Sorted Array is ");
for(int i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}