Sorting Using Quick Sort Algorithm
Sorting Using Quick Sort Algorithm
/* a[] is the array, p is starting index, that is 0, and r is the last index of
array. */ "
void quicksort(int a[], int p, int r)
{
if(p < r)
{
int q;
q = partition(a, p, r);
quicksort(a, p, q);
quicksort(a, q+1, r);
}
}
int partition(int a[], int p, int r)
{
int i, j, pivot, temp;
pivot = a[p];
i = p;
j = r;
while(1)
{
while(a[i] < pivot && a[i] != pivot)
i++;
while(a[j] > pivot && a[j] != pivot)
j--;
if(i < j)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
else
{
return j;
}
}
2.) Comparing 44 to the right hand -side elements, and if the element
present in right-side elements is smaller than 44 , then swap it. As 22 is
smaller than 44 so swap them.
22 33 11 55 77 90 40 60 99 44 88 66
3.) Now comparing 44 to the left side element and the element present on
the left hand side must be greater than 44 then swap them. As 55 is
greater than 44 so swap them.
22 33 11 44 77 90 40 60 99 55 88 66
4.) Repeating steps 1 & steps 2 until we get two lists one from the left of
pivot element 44 & one to the right hand side of pivot element.
22 33 11 40 77 90 44 60 99 55 88 66
22 33 11 40 44 90 77 60 99 55 88 66
(sublist 1) (Sublist 2)
And these sublists are sorted under the same steps as above done.
These two sorted sublists side by side.
First sublist:
22,33,11,40 in which i=22,j=40 and pivot=22 so scan right to left simply 11
is less than “<” pivot so interchange list :
90,77,60,99,55,88,66
so here i=90(pivot) and j=66 so here j= 66 is less than 90 so interchange in
right to left scan
see list:
66,77,60,99,55,88,90
66,77,60,90,55,88,99
66,77,60,88,55 and 90,99 because all elements left side of pivot less than
pivot and right side greater than pivot so again take first sublist
55,77,60,88,66
55,66,60,88,77
55,60,66,88,77
11,22,33,40,44,55,60,66,77,88,90,99