Quick sort

Quick sort

#include<stdio.h>
void quicksort(int,int);
int partition(int,int);
int a[100],n;
main()
{
 int i;
 printf("Enter limit \n");
 scanf("%d",&n);
 printf("Enter %d elements \n",n);
 for(i=0;i<n;i++)
  scanf("%d",&a[i]);
 printf("Before sorting \n");
 for (i=0;i<n;i++)
  printf("%d\t",a[i]);
 quicksort(0,n-1);
 printf("Afer sorting\n");
 for(i=0;i<n;i++)
  printf("%d\t",a[i]);
}
void quicksort(int lb,int ub)
{
 int newub;
 if (lb<ub)
 {
  newub=partition(lb,ub);
  quicksort(lb,newub-1);
  quicksort(newub+1,ub);
 }
}
int partition(int lb,int ub)
{
 int temp,down=lb,up=ub,pivot=a[lb];
 while (down<up)
 {
  while (pivot>=a[down] && down<=up)
   down=down+1;
  while (pivot<a[up])
   up=up-1;
  if (down<up)
  {
   temp=a[down];
   a[down]=a[up];
   a[up]=temp;
  }
 }
temp=a[lb];
a[lb]=a[up];
a[up]=temp;
return up;
}
 
Output


No comments:

Post a Comment