Sorting

์—ด๊ฑฐ๋œ ๋ฐ์ดํ„ฐ๋ฅผ ๊ธฐ์ค€ ์ˆœ์„œ (์˜ค๋ฆ„์ฐจ์ˆœ, ๋‚ด๋ฆผ์ฐจ์ˆœ ๋“ฑ๋“ฑ) ์— ๋งž๊ฒŒ ์ƒˆ๋กœ ์ •๋ฆฌํ•˜๋Š” ๊ธฐ๋ฒ•์„ ๋งํ•œ๋‹ค.

์ •๋ ฌ ์†๋„

Big-O ํ‘œ๊ธฐ๋ฒ•

์‹œ๊ฐ„ ๋ณต์žก๋„ ๋ฐ ๊ณต๊ฐ„๋ณต์žก๋„๋ฅผ ์ˆ˜์น˜ํ™”ํ•˜์—ฌ ํ‘œ๊ธฐํ•˜๋ฉฐ ๋ฉ”๋ชจ๋ฆฌ ๋ฐ ์„ฑ๋Šฅ์„ ๊ธฐ์ค€์œผ๋กœ ํ‰๊ท ์ ์ธ ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ๋‚˜ํƒ€๋‚ธ๊ฒƒ์œผ๋กœ ์ตœ์„  ๋ฐ ์ตœ์•…์˜ ์ˆ˜๋ฅผ ํ‘œํ˜„ํ•œ๋‹ค.

ํ€ต ์ •๋ ฌ (Quick Sort)

์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜์ค‘์—์„œ ๊ฐ€์žฅ ๋น ๋ฅธ ์ •๋ ฌ์ด๋‹ค.
๊ธฐ์ค€์ด ๋˜๋Š” ํ”ผ๋ฒ— ๋…ธ๋“œ์— ๋”ฐ๋ผ ์„ฑ๋Šฅ์ด ์ขŒ์šฐ๋œ๋‹ค.

์‹œ๊ฐ„ ๋ณต์žก๋„

  • ํ‰๊ท  O(n log n) ๋กœ ์†Œ์š”๋˜๋ฉฐ ์ผ๋ฐ˜์ ์œผ๋กœ ์‚ฌ์šฉ๋  ๋•Œ๋Š” ์ด๋ณด๋‹ค ๋น ๋ฅด๋‹ค.
  • ์ตœ์•…์˜ ๊ฒฝ์šฐ์—๋Š” O(n^2) ์œผ๋กœ ์†Œ์š”

ํŠน์ด์‚ฌํ•ญ

  • ๊ธฐ์ค€์ด ๋˜๋Š” Pivot ๋…ธ๋“œ์— ๋”ฐ๋ผ ์„ฑ๋Šฅ์ด ๋‹ฌ๋ผ์ง„๋‹ค.

๋จธ์ง€ ์ •๋ ฌ (Merge Sort)

์ •๋ ฌํ•˜๋ ค๋Š” ๋ฐฐ์—ด์„ ๋ฐ˜์œผ๋กœ ๋‚˜๋ˆ  ์ตœ์†Œ์˜ ํŒŒํ‹ฐ์…˜์œผ๋กœ ๋‚˜๋ˆ„๊ณ  ์ •๋ ฌํ•œ ํ›„ ๋จธ์ง€ํ•˜๋ฉด์„œ ์ •๋ ฌ

์‹œ๊ฐ„ ๋ณต์žก๋„

  • O(n log n) ์œผ๋กœ ํ€ต ์ •๋ ฌ๊ณผ ๊ฐ™๋‹ค.

ํŠน์ด์‚ฌํ•ญ

  • ๋ณ„๋„์˜ ์ €์žฅ ๊ณต๊ฐ„์ด ํ•„์š” ํ•˜๋‹ค.

Case 1 : JS - ES5

var arr = [6, 3, 8, 4, 1, 9, 2, 5, 7, 0];

function MergeSort(arr) {
  this.arr = null;

  if (arr instanceof Array) {
    this.arr = arr;
    return this.sort(arr);
  }
}

MergeSort.prototype = (function () {
  function sort(arr) {
    if (typeof arr === 'undefined' || !(arr instanceof Array)) {
      if (!(this.arr instanceof Array)) {
        throw new Error('Array object is not exist');
      }
      arr = this.arr;
    }

    if (arr.length === 1) {
      return arr;
    }

    var mid = Math.floor(arr.length / 2),
      left = arr.slice(0, mid),
      right = arr.slice(mid);

    return merge(sort(left), sort(right));
  }

  function merge(left, right) {
    var answer = [],
      leftLength = left.length,
      rightLength = right.length,
      leftIdx = 0,
      rightIdx = 0;

    while (leftIdx < leftLength && rightIdx < rightLength) {
      if (left[leftIdx] < right[rightIdx]) {
        answer.push(left[leftIdx]);
        leftIdx++;
      } else {
        answer.push(right[rightIdx]);
        rightIdx++;
      }
    }

    return answer.concat(left.slice(leftIdx), right.slice(rightIdx));
  }

  return {
    sort: sort
  };
}());
console.log(new MergeSort(arr));
var ms = new MergeSort();

console.log(ms.sort(arr));

์‚ฝ์ž… (Insertion)

์ „์ฒด์š”์†Œ์—์„œ ๊ฐ€์žฅ ์ž‘์€ ๋ฐ์ดํ„ฐ๋ฅผ ์ฐพ์•„ ๊ฐ€์žฅ ์•ž์˜ ๋ฐ์ดํ„ฐ์™€ ๊ตํ™˜ํ•˜๋Š” ๋ฐฉ์‹


const array = [5, 3, 1, 4, 2];

let len = array.length, i = 1, j, temp;

for (; i < len; ++i) {
  temp = array[i];
  j = i;

  while (j > 0 && array[j - 1] > temp) {
    array[j] = array[j - 1];

    j--;
    cnt++;
  }

  array[j] = temp;
}

console.log(array.join(' '));

์„ ํƒ (Selection)

์ „์ฒด ์š”์†Œ์—์„œ ๊ธฐ์ค€ ์œ„์น˜์— ๋งž๋Š” ์›์†Œ๋ฅผ ์„ ํƒํ•˜์—ฌ ๊ตํ™˜ํ•˜๋Š” ๋ฐฉ์‹

๋ฒ„๋ธ” (Bubble)

์™ผ์ชฝ ๋์—์„œ ๋ถ€ํ„ฐ ์ธ์ ‘ํ•˜๋Š” ๋‘ ํ•ญ๋ชฉ์˜ ๊ฐ’์„ ๋น„๊ตํ•˜์—ฌ ์„œ๋กœ ์œ„์น˜๋ฅผ ๊ตํ™˜ํ•˜๋Š” ์ •๋ ฌ ๋ฐฉ๋ฒ•