simple, slow | fast | O(N) |
---|---|---|
Selection sort, Bubble sort, Insertion sort | Quicksort, Merge sort, Heap sort | radix sort |
O(n^2)
// 오름차순, 최소값을 맨 앞자리와 바꾸는 방식
function selectionSort(arr) {
const len = arr.length
let minIndex = 0
let temp = 0
let i = 0
let j = 0
for (i = 0; i < len; i++) {
minIndex = i
for (j = i + 1; j < len; j++) {
if (arr[i] > arr[j]) {
minIndex = j
}
}
temp = arr[minIndex]
arr[minIndex] = arr[i]
arr[i] = temp
}
return arr
}
const arr = [1, 2, 5, 6, 4, 7, 9, 8, 3]
console.log(selectionSort(arr))
O(n^2)
// 오름차순
function bubbleSort(arr) {
const len = arr.length
let temp = 0
let i = 0
let j = 0
for (i = 0; i < len; i++) {
for (j = i + 1; j < len; j++) {
if (arr[i] > arr[j]) {
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
}
return arr
}
const arr = [1, 2, 5, 6, 4, 7, 9, 8, 3]
console.log(bubbleSort(arr))
O(n^2)
function insertionSort(arr) {
const len = arr.length
let temp = 0
for (i = 1; i < len; i++) {
for (let j = i - 1; j >= 0; j--) {
if (arr[i] < arr[j]) {
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
i--
}
}
}
return arr
}
const arr = [1, 2, 5, 6, 4, 7, 9, 8, 3]
console.log(insertionSort(arr))
function insertionSort(arr) {
for (let i = 0; i < arr.length; i++) {
index = i;
while (arr[index] !== undefined && arr[index - 1] > arr[index]) {
let temp = arr[index - 1];
arr[index - 1] = arr[index];
arr[index] = temp;
index--;
}
}
}
Photo by Michael Dziedzic on Unsplash