태그 : algorithm quick-sort

퀵정렬

퀵정렬은 pivot보다 작은수를 왼쪽에 큰수를 오른쪽에 두도록 스왑을 진행한다.

완료되면 pivot을 작은수와 큰수 사이에 오도록하고.

이후 다시 새로운 pivot을 기준으로 위와같이 그룹을 나누는 과정을 반복하는 재귀적 정렬방식이다.

ℹ️ 퀵정렬분석 참고링크 : 칸아카데미

퀵정렬은 보통 시간복잡도를 이야기할 때 평균복잡도로 이야기 한다.

최악의 경우 N^2의 경우가 나올 수 있다. 이 경우는 이미 정렬된 상태의 수열의 피봇을 가장 작은수 혹은 가장 큰수로 지정했을 때이고

나열되는 수열이 크면클수록 거의 그런 최악의 경우는 발생하지 않는다.

최악의 경우

quicksort

T(N) = C(n + n-1 + n-2 + ... 2) = O(N^2) [이유는? 등차수열의 합을 통해 확인]

최선의 경우

quicksort

T(N) = T(hight of partioning) * C * N = O(Nlog2(N))

최선의 결과로는 O(Nlog2(N))이 되는데 머지정렬과 동일한 시간복잡도가 나오나 실제로 테스트해보면 퀵정렬이 머지정렬보다 더 빠름.

ℹ️ 참고로 log2(N)의 과정은 머지정렬에 설명이 되어있음.

참고영상

Quick Sort 구현

 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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
function getSplitArrayIndex(arr, left, right, pivotIndex) {
  let temp;
  let pivot = arr[pivotIndex];
  while (left <= right) {
    while (arr[left] < pivot) {
      left++;
    }
    while (arr[right] > pivot) {
      right--;
    }
    if (left <= right) {
      temp = arr[left];
      arr[left] = arr[right];
      arr[right] = temp;
      left++;
      right--;
    }
  }
  temp = arr[left];
  arr[left] = arr[pivotIndex];
  arr[pivotIndex] = temp;
  return left;
}

function quickSort(arr, left, right) {
  if (!left) {
    left = 0;
  }
  if (!right) {
    right = arr.length - 1;
  }
  let pivotIndex = right;
  pivotIndex = getSplitArrayIndex(arr, left, right - 1, pivotIndex);
  if (left < pivotIndex - 1) {
    quickSort(arr, left, pivotIndex - 1);
  }
  if (pivotIndex + 1 < right) {
    quickSort(arr, pivotIndex + 1, right);
  }

  return arr;
}

var arr = [5, 1, 3, 4, 2];
console.log(arr);
console.log(quickSort(arr));
◀️ 선택 정렬 삽입 정렬 ▶️
comments powered by Disqus