-
Notifications
You must be signed in to change notification settings - Fork 0
/
quicksort.c
70 lines (60 loc) · 1.05 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
63
64
65
66
67
68
69
70
#include<stdio.h>
#define MAX 20
void quicksort(int [],int ,int ,int );
int partition (int [],int ,int ,int );
void print(int [],int );
void main()
{
int a[MAX],n,i;
printf("Enter array length:");
scanf("%d",&n);
printf("\nEnter array:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Before sorting:\n");
print(a,n);
quicksort(a,0,n-1,n);
printf("\nAfter sorting:\n");
print(a,n);
}
void print(int a[MAX],int n)
{
int i;
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
void quicksort(int a[MAX],int low,int high,int n)
{
int j,i;
if(low<high)
{
j=partition(a,low,high,n);
quicksort(a,low,j,n);
quicksort(a,j+1,high,n);
}
}
int partition(int a[MAX],int low ,int high,int n)
{
int pivot,i,j,temp,mid;
i=low-1;
j=high+1;
mid=(low+high)/2;
pivot=a[mid];
while(j>=i)
{
do{i++;}while(a[i]<pivot);
do{j--;}while(a[j]>pivot);
if(j>i)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
i++;
j--;
}
}
/* temp=a[j];
a[j]=a[mid];
a[mid]=temp;*/
return j;
}