Thursday, 7 May 2015

QUICK SORT [WITHOUT RECURSION]

 DESCRIPTION

Quick sort (sometimes called partition-exchange sort) is an efficient sorting algorithm, serving as a systematic method for placing the elements of an array in order. Developed by Tony Hoare in 1959  (published 1962), it is still a very commonly used algorithm for sorting. When implemented well, it can be about two or three times faster than its main competitors, merge sort and heap sort.
Quick sort is a comparison sort, meaning that it can sort items of any type for which a "less-than" relation (formally, a total order) is defined. In efficient implementations it is not a stable sort, meaning that the relative order of equal sort items is not preserved. Quick sort can operate in-place on an array, requiring small additional amounts of memory to perform the sorting.
Mathematical analysis of quick sort shows that, on average, the algorithm takes O(n log n) comparisons to sort n items. In the worst case, it makes O(n2) comparisons, though this behavior is rare


PROGRAM

#include<stdio.h>
#include<conio.h>

int partition(int a[],int l,int u);
int n;
void main()
{
   int a[20],n,i,top=0,l,u,s,lower[10],upper[10];
   clrscr();
   printf("Enter the size of array:");
   scanf("%d",&n);
   printf("Enter the elements to be sorted:");
   for(i=1;i<=n;i++)
   scanf("%d",&a[i]);
   if(n>1)
       {
            top=top+1;
            lower[top]=1;
            upper[top]=n;
       }
      while(top!=0)
      {
            l=lower[top];
            u=upper[top];
            top=top-1;
            s=partition(a,l,u);
            if(l<s-1)
             {
              top=top+1;
              lower[top]=1;
              upper[top]=s-1;
             }
            if(s+1<u)
             {
              top=top+1;
              lower[top]=s+1;
              upper[top]=u;
             }

      }
   printf("The sorted array is:");
   for(i=1;i<=n;i++)
   printf("%d ",a[i]);
   getch();
 }



  int partition(int a[],int l,int u)
  {
   int i,j,temp,p,flag;
    i=l;
    j=u+1;
    p=a[l];
    flag=1;
   while((flag==1)&&(j>1))
    {
      i=i+1;
      while(a[i]<p&&i<=n)
       {
            i++;
       }
      j=j-1;
      while(a[j]>p&&j>l)
       {
            j--;
       }
      if(i<j)
       {
            temp=a[i];
            a[i]=a[j];
            a[j]=temp;
       }
      else
       flag=0;
    }
     a[l]=a[j];
     a[j]=p;
     return j;
 }

OUTPUT
Enter the limit of the array : 4
enter the element to be sorted :9 5 7 2

the sorted array is :2 5 7 9

No comments:

Post a Comment