Difference between revisions of "Interview Preparation Quick Sort"

From Embedded Systems Learning Academy
Jump to: navigation, search
(Created page with "Algorithm for implementation of quick sort is as follows a. Any element can be marked as a pivot but in this algorithm, I am using the starting index as a pivot. b. Divide...")
 
Line 10: Line 10:
  
 
e. consider right part and repeat step b,c,d and e until all the elements are sorted.
 
e. consider right part and repeat step b,c,d and e until all the elements are sorted.
 +
 +
'''Code snippet'''
 +
<pre>
 +
if (start < end)
 +
    {
 +
        pivot = start;
 +
        i = start;
 +
        j = end;
 +
        while (i < j)
 +
        {
 +
            while (array[i] <= array[pivot] && i <= end)
 +
            {
 +
                i++;
 +
            }
 +
            while (array[j] > array[pivot] && j >= start)
 +
            {
 +
                j--;
 +
            }
 +
            if (i < j)
 +
            {
 +
                temp = array[i];
 +
                array[i] = array[j];
 +
                array[j] = temp;
 +
            }
 +
        }
 +
        temp = array[j];
 +
        array[j] = array[pivot];
 +
        array[pivot] = temp;
 +
        quicksort(array, start, j - 1);
 +
        quicksort(array, j + 1, end);
 +
}</pre>
 +
  
 
For an array with n number of elements,
 
For an array with n number of elements,

Revision as of 13:22, 25 November 2016

Algorithm for implementation of quick sort is as follows

a. Any element can be marked as a pivot but in this algorithm, I am using the starting index as a pivot.

b. Divide the array such that, All the element that are less than pivot are kept in one part and other are kept in another part.

c. Now pivot can be placed at its position between two parts.

d. consider only left part and repeat the step b and c until only one element is left.

e. consider right part and repeat step b,c,d and e until all the elements are sorted.

Code snippet

 if (start < end)
    {
        pivot = start;
        i = start;
        j = end;
        while (i < j) 
        {
            while (array[i] <= array[pivot] && i <= end)
            {
                i++;
            }
            while (array[j] > array[pivot] && j >= start)
            {
                j--;
            }
            if (i < j)
            {
                temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }
        }
        temp = array[j];
        array[j] = array[pivot];
        array[pivot] = temp;
        quicksort(array, start, j - 1);
        quicksort(array, j + 1, end);
}


For an array with n number of elements,

Best case complexity = Average case complexity = O(n log n).

Worst case complexity = O(n^2).