Program 4
Program 4
(8522109)
Program No-6
Aim: Write a program to implement Quick Sort
Description: Quick Sort is a sorting algorithm which is based on Divide and
Conquer strategy. It picks an element as a pivot and uses partition procedure to
sort the array around the picked pivot.
Source code:
#include<stdio.h>
int partition(int a[], int p, int r)
{
int temp, j;
int x=a[r];
int i =p-1;
for(j=p; j<r; j++)
{
if (a[j]<=x)
{
i++;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[i+1];
a[i+1]=a[r];
a[r]=temp;
return i+1;
}
void quicksort(int a[], int p, int r)
{
if (p<r)
{
int q=partition(a,p,r);
quicksort(a,p,q-1);
quicksort(a,q+1,r);
}
}
int main()
{
int a[20], i,n;
printf("enter the size of array:");
scanf ("%d",&n);
printf ("enter elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
quicksort(a,0,n-1);
printf("sorted array:");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
return 0;
}
Output: