Docsity

Sorting algorithm - Quick sort, Slides of Data Structures and Algorithms

Partial preview of the text

Download Sorting algorithm - Quick sort and more Slides Data Structures and Algorithms in PDF only on Docsity!

i j

26^5 19 1 15 11 59 61 48 37

26^5 19 1 15 11 59 61 48 37

[11^5 19 1 15]^26 [59^61 48 37]

[11^5 19 1 15]^26 [59^61 48 37]

[11^5 19 1 15]^26 [59^61 48 37]

[11^5 1 19 15]^26 [59^61 48 37]

[11^5 1 19 15]^26 [59^61 48 37]

[11^5 1 19 15]^26 [59^61 48 37]

[1 5]^11 [19^ 15]^26 [59^61 48 37]

[1 5]^11 [15^ 19]^26 [59^61 48 37]

[1 5]^11 [15^ 19]^26 [59^61 48 37]

[1 5]^11 [15^ 19]^26 [59^61 48 37]

  • (^) In Quick sort take the first element as pivot element
  • (^) In Quick sort first find the correct position of pivot element and place it at the correct position
  • (^) Find the element greater than pivot element from the left and find the element less than the pivot element from the right
  • (^) Interchange the elements in left and right this process continues till left crosses the right
  • (^) When left crosses right interchange the element from the right that is less than the pivot element with the pivot element
  • (^) Now the pivot element is at the correct position and apply Quick sort to the left and right of pivot element recursively and continue this process

do { do i++; while(x [i] < pivot); do j--; while( x[j] > pivot); if (i<j) Interchange(x, i, j); } while (i<j); Interchange(x, left, j); Quicksort(x, left, j-1); Quicksort(x, j+1, right); } }

Interchange (int x[ ], int k, int c) { int temp; temp = x[k]; x[k] = x[c]; x[c] = temp; } The best case of Quick sort is O(n logn) and the worst case is O(n 2 ).