Quick sort - 401-advanced-javascript-v/seattle-javascript-401d29 GitHub Wiki

Quick sort

Learning Objectives

  • What is quick sort
  • How to describe the Algorithm
  • How does it visually looks like
  • What's the pseudocode
  • How to implement

Lecture Flow

Main Point

Quick sort is based on the divide-and-conquer approach based on the idea of choosing one element as a pivot element and partitioning the array around it such that: Left side of pivot contains all the elements that are less than the pivot element Right side contains all elements greater than the pivot

It reduces the space complexity and removes the use of the auxiliary array that is used in merge sort. Selecting a random pivot in an array results in an improved time complexity in most of the cases.

Diagram

Algorithm--pivot

-Step 1 − Choose the highest index value has pivot -Step 2 − Take two variables to point left and right of the list excluding pivot -Step 3 − left points to the low index -Step 4 − right points to the high -Step 5 − while value at left is less than pivot move right -Step 6 − while value at right is greater than pivot move left -Step 7 − if both step 5 and step 6 does not match swap left and right -Step 8 − if left ≥ right, the point where they met is new pivot

Pseudocode--pivot

function partitionFunc(left, right, pivot) leftPointer = left rightPointer = right - 1

while True do while A[++leftPointer] < pivot do //do-nothing
end while

  while rightPointer > 0 && A[--rightPointer] > pivot do
     //do-nothing         
  end while
	
  if leftPointer >= rightPointer
     break
  else                
     swap leftPointer,rightPointer
  end if

end while

swap leftPointer,right return leftPointer

end function

Algorithm--quick sort

-Step 1 − Make the right-most index value pivot -Step 2 − partition the array using pivot value -Step 3 − quicksort left partition recursively -Step 4 − quicksort right partition recursively

Pseudocode--quick sort

procedure quickSort(left, right)

if right-left <= 0 return else
pivot = A[right] partition = partitionFunc(left, right, pivot) quickSort(left,partition-1) quickSort(partition+1,right)
end if

end procedure

Readings and References

Read