You are on page 1of 3

Quick sort:

Quick sort is one of the fastest and simplest sorting algorithms. quick sort algorithm was developed in 1960
by C. A. R. . It has two phases, the partition phase and the sort phase.
Partition Phase :it works out where to divide the work.
Sort Phase: The sort phase simply sorts the two smaller problems that are generated in the partition phase.

QUICKSORT (A ,p ,r)
1.If p < r
2.q =PARTITION(A ,p ,r)
3.QUICKSORT(A,p,q-1)
4.QUICKSORT(A,q+1,r)
Here A is Entry Array.

Partitioning the Array :


The key To the algorithm is the PARTITION Procedure ,which rearranges the sub array A [p…r] in place .

PARTITION(A ,p ,r)
1. X=A [r]
2. i= p-1
3. For j=p to r-1
4. If A [j] ≤ x
5. i=i+1
6. Exchange A [i] with A [j]
7. Exchange A [ i+1] with A [r]
8. Return i+1

2 8 7 1 3 5 6 4

Here P=1 ,r=8 so p < r


X=A [r] ,A[8]=4 x=4
i=p-1,i=1-1=0
For J=1
If A [j]=A[1]=2 here A [j] ≤x because 2 ≤4 ,so condition True
i=i+1 ,i=0+1=1
Exchange A [i] with A [j] so A[1] with A[1]
For j=2
If A [j]=A[2]=8 here A [j] ≤x not True ,so condition false
For j=3
A [j]=A[3]=7,here A [j] ≤x not True ,so condition false
For j=4
If A [j]=A[4]=1, here A [j] ≤x because 1 ≤4 ,so condition True
i=i+1,i=1+1=2
Exchange A [i] with A [j] so A[2] with A[4]
For j=5
If A [j]=A[5]=3, here A [j] ≤x because 3 ≤4 ,so condition True
i=i+1,i=2+1=3
Exchange A [i] with A [j] so A[3] with A[5]
For j=6
A [j]=A[6]=5,here A [j] ≤x not True ,so condition false
For j=7
A [j]=A[7]=6,here A [j] ≤x not True ,so condition false ,End For Loop
Now ,Exchange A[i+1] with A [r] Here A[3+1]=A[4] with A[8]
2 8 7 1 3 5 6 4

2 1 7 8 3 5 6 4

2 1 3 8 7 5 6 4

2 1 3 4 7 5 6 8

1 2 3 4 5 6 7 8

#include<stdio.h>
#define SIZE 50

int arry[SIZE] ;
void quicksort(int arry[], int p, int r);
int partition(int arry[], int p, int r);

void main()
{
int i,Num=0;
printf("Number of element: ");
scanf("%d", &Num);
printf("Enter %d elements :",Num);
for(i = 0; i<Num; i++)
scanf("%d",&arry[i]);

quicksort(arry,0,Num-1);
printf("elements after sorted\n");
for(i = 0; i<Num; i++)
printf("%d ",arry[i]);
}

void quicksort(int arry[], int p, int r)


{
int q;
if (p < r)
{
q = partition(arry, p, r);
quicksort(arry, p, q-1);
quicksort(arry, q+1, r);
}
}

int partition(int arry[], int p, int r)


{
int temp;
int x = arry[r];
int i = p - 1;
int j = p;

for(j=p;j<=r-1;j++)
{
if (arry[j]<=x)
{
i=i+1;

temp = arry[i];
arry[i] = arry[j];
arry[j] = temp;
}
}
temp=arry[i+1];
arry[i+1]=arry[r];
arry[r]=temp;

return i+1;
}

You might also like