Friday, July 22, 2011

Progrma for quick sort

/*Serial No.160     [swami141.cpp]*/

#include<stdio.h>
#include<conio.h>
#define MAX 10
    
int arr[MAX],num,n;
    
void quicksort(int,int);
void main()
{
int i,first,last;
clrscr();
printf("Enter the number of elements in the list: ");
scanf("%d",&n);
printf("Enter the elements: \n");
for(i=0;i<n;i++)
        {
        scanf("%d",&arr[i]);
        }
quicksort(0,n-1);// pass the first and last index
printf("The sorted elements: \n");
for(i=0;i<n;i++)
        {
         printf("%d..\n",arr[i]);
        }
getch();
}
    
void quicksort(int first,int last)
       {
        int temp,low,high,midval;
        low=first;//array index
        high=last;//array index
        midval=arr[(first+last)/2]; // mid element
    
        do
        {
            while(arr[low]<midval)
            {
                low++;
            }
            while(arr[high]>midval)
            {
                high--;
            }
            if(low<=high)
            {
                temp=arr[low];
                arr[low]=arr[high];
                arr[high]=temp;
                low++;
                high--;
            }
        }while(low<=high);
        if(first<high)
        {
            quicksort(first,high);
        }
        if(low<last)
        {
            quicksort(low,last);
        }
    }

No comments:

Post a Comment

If you have any doubt, feel free to ask...