function bubbleSort(arr) {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - i; j++) {
if (arr[j] > arr[j + 1]) {
const swap = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = swap;
}
}
}
return arr;
}
const arr = [4, 3, 8, 5, 2, 1];
console.log(bubbleSort(arr)); // [1, 2, 3, 4, 5, 8]
function selectionSort(arr) {
for (let i = 0; i < arr.length; i++) {
let minIndex = i;
for (let j = i + 1; j < arr.length; j++) {
if (arr[minIndex] > arr[j]) {
minIndex = j;
}
}
const swap = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = swap;
}
return arr;
}
const arr = [99, 3, 7, 9, 5, 10, 25, 17];
console.log(selectionSort(arr)); // [3, 5, 7, 9, 10, 17, 25, 99]
function insertionSort(arr) {
for(let i = 1; i < arr.length; i++) {
let cur = arr[i];
let left = i - 1;
while(left >= 0 && arr[left] > cur) {
arr[left + 1] = arr[left];
left--;
}
arr[left + 1] = cur;
}
return arr;
}
const arr = [5, 3, 7, 39, 28, 6, 1];
console.log(insertionSort(arr)); // [1, 3, 5, 6, 7, 28, 39]
function mergeSort(arr) {
if (arr.length <= 1) return arr;
const mid = Math.floor(arr.length / 2);
const left = arr.slice(0, mid);
const right = arr.slice(mid);
return merge(mergeSort(left), mergeSort(right));
}
function merge(left, right) {
const result = [];
while(left.length && right.length) {
if(left[0] < right[0]) {
result.push(left.shift());
} else {
result.push(right.shift());
}
}
while(left.length) {
result.push(left.shift());
}
while(right.length) {
result.push(right.shift());
}
return result;
}
const arr = [3, 5, 2, 8, 9, 1, 9, 39, 28];
console.log(mergeSort(arr)); // [1, 2, 3, 5, 8, 9, 9, 28, 39]
function quickSort(arr) {
if (arr.length <= 1) return arr;
const pivot = arr[0];
const left = [];
const right = [];
for (let i = 1; i < arr.length; i++) {
if (arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return quickSort(left).concat(pivot, quickSort(right));
}
const arr = [4, 8, 2, 1, 3, 5, 9];
console.log(quickSort(arr)); // [1, 2, 3, 4, 5, 8, 9]
정렬 알고리즘 정리(With Big O Notation)
[알고리즘] 퀵 정렬(quick sort)이란
Big-O Notation Explained