-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquick-sort.c
62 lines (56 loc) · 943 Bytes
/
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
#include <stdio.h>
#include <conio.h>
int partition(int a[], int start, int end);
void quickSort(int a[], int start, int end);
void swap(int *x, int *y);
int main()
{
int i;
int ar[]={7,2,1,6,8,5,3,9};
//clrscr();
printf("Unsorted array:\n");
for(i=0;i<8;i++)
{
printf("%d ",ar[i]);
}
quickSort(ar,0,7);
printf("\nSorted array:\n");
for(i=0;i<8;i++)
{
printf("%d ",ar[i]);
}
//getch();
return 0;
}
void quickSort(int a[], int start, int end)
{
int p;
if(start < end)
{
p = partition(a,start,end);
quickSort(a,start,p-1);
quickSort(a, p+1, end);
}
}
int partition(int a[], int start, int end)
{
int i,p=start; //partition index
int pivot=a[end];
for(i=start;i<end;i++)
{
if(a[i]<=pivot)
{
swap(&a[i],&a[p]);
p++;
}
}
swap(&a[p],&a[end]);
return p;
}
void swap(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}