How to implement quicksort in javascript?

Member

by elnora , in category: JavaScript , a year ago

How to implement quicksort in javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by ola.stoltenberg , a year ago

@elnora 

Here is an example of how to implement quicksort in JavaScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
function quickSort(arr) {
  if (arr.length <= 1) {
    return arr;
  }

  const pivot = arr[arr.length - 1];
  const left = [];
  const right = [];

  for (let i = 0; i < arr.length - 1; i++) {
    if (arr[i] < pivot) {
      left.push(arr[i]);
    } else {
      right.push(arr[i]);
    }
  }

  return [...quickSort(left), pivot, ...quickSort(right)];
}

const sortedArray = quickSort([5, 2, 1, 8, 4, 7, 6, 3]);
console.log(sortedArray);  // prints [1, 2, 3, 4, 5, 6, 7, 8]


This implementation works by selecting a pivot element from the array and partitioning the other elements into two subarrays, according to whether they are less than or greater than the pivot. The subarrays are then sorted recursively using the same quickSort function.


The pivot element can be chosen in different ways. In the example above, the pivot is the last element of the array. Other common strategies for choosing the pivot include selecting the first element, the middle element, or a random element of the array.


I hope this helps! Let me know if you have any questions.

by audrey.hodkiewicz , 4 months ago

@elnora 

The quickSort function takes an array as input and recursively sorts it using the quicksort algorithm. Here's how it works:

  1. The function starts by checking the base case - if the input array has a length of 1 or less, it means it is already sorted, so it returns the array as is.
  2. If the base case is not met, the function selects the pivot element. In this implementation, the pivot is chosen as the last element of the array, but you can choose a different pivot selection strategy.
  3. The next step is to create two empty arrays - 'left' and 'right'. These arrays will store the elements smaller than the pivot and the elements greater than the pivot, respectively.
  4. A for loop runs through all the elements of the input array, except for the last element (which is the pivot). If an element is smaller than the pivot, it is pushed into the 'left' array. Otherwise, it is pushed into the 'right' array.
  5. Finally, the function returns the concatenation of three arrays - the recursively sorted 'left' array, the pivot, and the recursively sorted 'right' array.
  6. The quickSort function is called to sort the array [5, 2, 1, 8, 4, 7, 6, 3]. The result is stored in the sortedArray variable.
  7. The sorted array is then printed to the console using console.log.


This implementation of quicksort has a time complexity of O(n log n) on average, with O(n^2) being the worst-case time complexity. The space complexity is O(log n).