2 Dec 2019

  • December 02, 2019
  • Amitraj
Quick sort

-> Quick sort is an efficient sorting algorithm which is based on divide and conquer algorithm. In this sorting technique it picks a pivot value and divide the given array around the picked pivot.


/* C program to implement Quick sort */


#include<stdio.h>
void quicksort(int a[20],int first,int last)
{
int temp,pivot,i,j;
if(first<last)
{
pivot=first;
i=first;
j=last;
while(i<j)
{
while(a[i]<=a[pivot]&&i<last)
i++;
while(a[j]>a[pivot])
j--;

if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[j];
a[j]=a[pivot];
a[pivot]=temp;
quicksort(a,first,j-1);
quicksort(a,j+1,last);
}
}
int main()
{
int n,i,a[20];
printf("Enter how many elements:");
scanf("%d",&n);
printf("enter %d numbers:",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
quicksort(a,0,n-1);
printf("Numbers in sorted order:");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
return 0;
}

OUTPUT:

Enter how many elements:5
enter 5 numbers:6 9 5 2 41
Numbers in sorted order:2       5       6       9       41


Translate

Popular Posts