/* QUICK sort is the fastest algorithm on random data of O(n log n) */
#include<stdio.h>
#include<stdlib.h>
#define N 100
void quick_sort(int *list,int start, int end);
main()
{
int i=0,list[N];
int key,size=1;
do
{
scanf("%d",&key);
if(key == -9999)
{
break;
}
else
{
list[i++] = key;
}
}while(1);
size = i;
printf("original \n");
for(i=0;i<size;i++)
{
printf("%d ",list[i]);
}
printf("\nSorted \n");
quick_sort(list,0,size-1);
for(i=0;i<size;i++)
{
printf("%d ",list[i]);
}
getchar();
getchar();
return 0;
}
/* This function does the quick sort recursively */
void quick_sort(int *list, int start,int end)
{
int i,j, pivot,temp;
/* Algo should end if start > = end*/
if(start<end)
{
/* store pivot and indexes*/
pivot = list[end];
i=start;
j=end-1;
while(i<j)
{
/* move i until list[i] < pivot*/
while(list[i] < pivot)
{
i++;
}
/* move j until list[j] > pivot */
while( (i < j) &&(list[j] > pivot))
{
j--;
}
/* interchange if required*/
if(i<j)
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
i++;
j--;
}
}
/* partition is done at i. move the pivot to i*/
if(i<end)
{
list[end] = list[i];
list[i] = pivot;
}
/*Call recursive*/
quick_sort(list,start,i-1);
quick_sort(list,i+1,end);
}
return;
}
No comments:
Post a Comment