-
Notifications
You must be signed in to change notification settings - Fork 0
/
Quick.c
65 lines (65 loc) · 1.55 KB
/
Quick.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
#include<stdio.h>
void swap (int a[], int left, int right)
{
int temp;
temp=a[left];
a[left]=a[right];
a[right]=temp;
} //end swap
int partition( int a[], int low, int high )
{
int left, right;
int pivot_item;
int pivot = left = low;
pivot_item = a[low];
right = high;
while ( left < right )
{
// Move left while item < pivot
while( a[left] <= pivot_item )
left++;
// Move right while item > pivot
while( a[right] > pivot_item )
right--;
if ( left < right )
swap(a,left,right);
}
// right is final position for the pivot
a[low] = a[right];
a[right] = pivot_item;
return right;
} //end partition
// void quicksort(int a[], int, int);
void quicksort( int a[], int low, int high )
{
int pivot;
// Termination condition!
if ( high > low )
{
pivot = partition( a, low, high );
quicksort( a, low, pivot-1 );
quicksort( a, pivot+1, high );
}
} //end quicksort
void printarray(int a[], int);
int main()
{
int a[50], i, n;
printf("\nEnter no. of elements: ");
scanf("%d", &n);
printf("\nEnter the elements:");
for (i=0; i<n; i++)
scanf ("%d", &a[i]);
printf("\nUnsorted input elements:");
printarray(a,n);
quicksort(a,0,n-1);
printf("\nSorted output elements:");
printarray(a,n);
} //end main
void printarray(int a[], int n)
{
int i;
for (i=0; i<n; i++)
printf(" %d ", a[i]);
printf("\n");
}//end printarray