All files / quickSort index.ts

100% Statements 29/29
100% Branches 12/12
100% Functions 1/1
100% Lines 29/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 301x 1x 1x 1x 11245x 11245x 11245x 1905x 1905x 5621x 5621x 5621x 5621x 5621x 5621x 11245x 165201x 165201x 76394x 76394x 165201x 83186x 83186x 165201x 5621x 5621x 5621x 1x 1x  
// quicksort idea
// Pick a pivot
//  then move all items less than pivot to left
const quickSort = (arr: number[]): number[] => {
  // base case
  if (!arr.length || arr.length === 1) return arr;
  if (arr.length == 2) {
    return [Math.min(...arr), Math.max(...arr)];
  }
 
  // recursion case
  const pivot = Math.floor(arr.length / 2);
  const greater = [];
  const less = [];
 
  for (let x = 0; x < arr.length; x++) {
    const item = arr[x];
    if (item >= arr[pivot] && x !== pivot) {
      greater.push(item);
    }
    if (item < arr[pivot] && x !== pivot) {
      less.push(item);
    }
  }
 
  return [...quickSort(less), arr[pivot], ...quickSort(greater)];
};
 
export default quickSort;