두 인접한 원소를 비교하여 정렬하는 방법이다.
JavaScript (오름차순)
function bubbleSort(array) {
const N = array.length;
for (let i = 0; i < N; i++) {
for (let j = 1; j < N; j++) {
if (array[j] < array[j - 1]) {
swap(array, j, j - 1);
}
}
}
}
function swap(array, aIdx, bIdx) {
const temp = array[aIdx];
array[aIdx] = array[bIdx];
array[bIdx] = temp;
}
Javascript (오름차순)
function selectionSort(Array) {
const N = Array.length;
for (let i = 0; i < N; i++) {
let min = Number.MAX_SAFE_INTEGER;
let minIdx;
for (let j = i; j < N; j++) {
if (min > Array[j]) {
min = Array[j];
minIdx = j;
}
}
swap(Array, i, minIdx);
}
}
function swap(array, aIdx, bIdx) {
const temp = array[aIdx];
array[aIdx] = array[bIdx];
array[bIdx] = temp;
}
JavaScript (오름차순)
function insertionSort(Array) {
const N = Array.length;
for (let i = 1; i < N; i++) {
const key = Array[i];
let insertIdx = i - 1;
while(insertIdx >= 0 && Array[insertIdx] > key) {
Array[insertIdx + 1] = Array[insertIdx];
insertIdx--;
}
Array[insertIdx + 1] = key;
}
}
function swap(array, aIdx, bIdx) {
const temp = array[aIdx];
array[aIdx] = array[bIdx];
array[bIdx] = temp;
}