본문 바로가기
✘✘✘ Algorithm + Data structure/자료구조

[sort] Quick sort, 퀵 소트- 1 pivot

by PrettyLog 2023. 4. 5.

function quickSort(arr) {
  quickSortRecursivley(arr, 0, arr.length - 1);
  return arr;
}

function quickSortRecursivley(arr, s, e) {
  if (s >= e) return;
  const pivotIndex = partition(arr, s, e);
  quickSortRecursivley(arr, pivotIndex + 1, e);
  quickSortRecursivley(arr, s, pivotIndex - 1);
}

function partition(arr, s, e) {
  let pivot = e;

  let left = s;
  let right = e;

  let pointer = left;
  let pivotNumber = arr[right];

  for (let i = left; i < right; i++) {
    if (arr[i] >= pivotNumber) continue;
    swap(arr, i, pointer);
    pointer++;
  }

  swap(arr, pointer, right);

  return pointer;
}

function swap(arr, a, b) {
  [arr[b], arr[a]] = [arr[a], arr[b]];
}

// Do not edit the line below.
exports.quickSort = quickSort;

댓글