I've been brushing up on some forgotten skills for a interview recently, mainly sorting algorithms, and I've come across two different ways to do quick sort and I'm having trouble telling which one is the proper way of doing it. Does anyone know which one is correct?
Version 1:
const quickSort(arr, start, end){
if (start >= end) {
return;
}
let index = partition(arr, start, end);
quickSort(arr, start, index - 1);
quickSort(arr, index + 1, end);
}
function partition(arr, start, end){
const pivotValue = arr[end];
let pivotIndex = start;
for (let i = start; i < end; i++) {
if (arr[i] < pivotValue) {
[arr[i], arr[pivotIndex]] = [arr[pivotIndex], arr[i]];
pivotIndex++;
}
}
[arr[pivotIndex], arr[end]] = [arr[end], arr[pivotIndex]]
return pivotIndex;
}
Version 2:
function QuickSort(Arr){
if(Arr.length < 2) return Arr;
const pivot = Arr[0];
const leftArr = [];
const rightArr = [];
for(let i = 1; i < Arr.length; i++){
if(Arr[i] < pivot){
leftArr.push(Arr[i]);
}
else{
rightArr.push(Arr[i])
}
}
return [...QuickSort(leftArr), pivot, ...QuickSort(rightArr)];
}