Tuesday, July 15, 2008

Program to sort list of elements using quick sort.


/**********************************************************************/

/*Program : To show sorting technique*/

/*Purpose : Program to sort list of elements using quick sort*/

/*Date : 04-01-2005*/

/*Time : 08:40*/

/**********************************************************************/

#include

#include

#define SIZE 20

/**************Function Declaration Begin**********/

void Quick_sort(int A[],int n);

int Partition(int A[],int n);

void get_elements(int A[],int n);

void show_elements(int A[],int n);

/**************Function Declaration End**********/

void main()

{

int n,A[SIZE];

clrscr();

printf(“\n\t\t Program for Quick sort:”);

printf(“\n\n\t\t How many numbers you want to store in the array:”);

scanf(“%d”,&n);

get_elements(A,n);

Quick_sort(A,n);

show_elements(A,n);

getch();

}

/********** inputting elements **********/

/********** Function Definition begins **********/

void get_elements( int A[],int n)

{

int i;

printf(“\n Enter %d elements\n”,n);

for (i=0;i

scanf(“%d”,&A[i]);

printf(“\n Array before sorting: “);

for(i=0;i

printf(“%d “,A[i]);

printf(“\n”);

}

/********** Function Definition ends **********/

/********** displaying elements **********/

/********** Function Definition begins **********/

void show_elements(int A[],int n)

{

int i;

printf(“\n Array after sorting: “);

for(i=0;i

{

printf(“%d “,A[i]);

}

printf(“\n”);

}

/********** Function Definition ends **********/

/******************* Quick Sorting technique *****************/

/********** Function Definition begins **********/

void Quick_sort(int A[],int n)

{

int pivot;

if(n<=1)

{

return;

}

pivot=Partition(A,n);

Quick_sort(A,pivot);

Quick_sort(A+pivot+1,n-pivot-1);

}

/********** Function Definition ends **********/

/******************* partitioning technique *****************/

/********** Function Definition begins **********/

int Partition(int A[],int n)

{

int pivot,l,r,s;

pivot=A[0]; /* Fixing first element as pivot*/

l=0; r=n-1;

for( ; ; )

{

while(l

{

l++;

}

while(lpivot)

{

r—;

}

if(l==r)

{

if(A[r]>pivot)

{

l=l-1;

}

break;

}

s=A[l];

A[l]=A[r];

A[r]=s;

}

s=A[0];

A[0]=A[l];

A[l]=s;

return l;

}

/********** Function Definition ends **********/

Ø OUTPUT

Program for Quick sort:

How many numbers you want to store in the array:6

Enter 6 elements

66

55

44

33

22

11

Array before sorting: 66 55 44 33 22 11

Array after sorting: 11 22 33 44 55 66

No comments: