Coding Interview Prep: Algorithms - Implement Quick Sort (freeCodeCamp)

 Implement Quick Sort

Here we will move on to an intermediate sorting algorithm: quick sort. Quick sort is an efficient, recursive divide-and-conquer approach to sorting an array. In this method, a pivot value is chosen in the original array. The array is then partitioned into two subarrays of values less than and greater than the pivot value. We then combine the result of recursively calling the quick sort algorithm on both sub-arrays. This continues until the base case of an empty or single-item array is reached, which we return. The unwinding of the recursive calls return us the sorted array.

Quick sort is a very efficient sorting method, providing O(nlog(n)) performance on average. It is also relatively easy to implement. These attributes make it a popular and useful sorting method.

Instructions: Write a function quickSort which takes an array of integers as input and returns an array of these integers in sorted order from least to greatest. While the choice of the pivot value is important, any pivot will do for our purposes here. For simplicity, the first or last element could be used.


Solution:


function quickSort(array) {
  // Only change code below this line  

  if(array.length < 1return []
  let pivot = array[0];
  let less = [];
  let great = [];
  let equal = [];

  for(let i=0;i<array.length;i++){
    if(array[i] > pivotgreat.push(array[i])
    else if(array[i] < pivotless.push(array[i])
    else equal.push(array[i]) 
  }

  let sortedArray = [...quickSort(less), ...equal, ...quickSort(great)]
  console.log(sortedArray)
  return sortedArray
  // Only change code above this line
}

quickSort([1,4,2,8,3,6,5,7])

thedawnsoft-quicksort

Click here to go to the original link of the question.

Post a Comment

Previous Post Next Post