Quick Sort

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

Write a program for Quick Sort

Algorithm:
1). Selecting Pivot

The process starts by selecting one element (known as the pivot) from the list; this can be
any element. A pivot can be:

 Any element at random

 The first or last element

 Middle element.

2). Rearranging the Array

Now, the goal here is to rearrange the list such that all the elements less than the pivot are
towards the left of it, and all the elements greater than the pivot are towards the right of it.

 The pivot element is compared to all of the items starting with the first index. If the
element is greater than the pivot element, a second pointer is appended.

 When compared to other elements, if a smaller element than the pivot element is
found, the smaller element is swapped with the larger element identified before.
Program:

/*Program On Quick Sort*/


#include<stdio.h>
#define max 100
int qsort(int a[max],int f,int l)
{
int i, j, p, temp;
if(f<l)
{
p=f;
i=f;
j=l;
while(i<j)
{
while(a[i]<=a[p]&&i<l)
i++;
while(a[j]>a[p])
j--;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[p];
a[p]=a[j];
a[j]=temp;
qsort(a,f,j-1);
qsort(a,j+1,l);
}
}
int main()
{
int i,n,a[max];
printf("Enter The Number Of Elements...\n");
scanf("%d",&n);
printf("Enter %d elements:\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
qsort(a,0,n-1);
printf("Order of Sorted elements after Using Quick Sort Technique:\n
");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
return 0;
}
Output:

Enter The Number Of Elements...


5
Enter 5 elements:
19
18
17
16
15
Order of Sorted elements after Using Quick Sort Technique:
15
16
17
18
19

You might also like