출처
1. 버블정렬
function bubbleSort(arr: number[]) {
for (let i = 0; i < arr.length; i++) {
for (let j = 1; j < arr.length - i; j++) {
if (arr[j] < arr[j - 1]) {
const temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
2. 선택정렬
function selectionSort(arr: number[]) {
for (let i = 0; i < arr.length - 1; i++) {
let indexMin = i;
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[indexMin]) {
indexMin = j;
}
}
const temp = arr[indexMin];
arr[indexMin] = arr[i];
arr[i] = temp;
}
return arr;
}
3. 삽입정렬
function insertionSort(arr: number[]) {
for (let index = 1; index < arr.length; index++) {
let temp = arr[index];
let aux = index - 1;
while (aux >= 0 && arr[aux] > temp) {
arr[aux + 1] = arr[aux];
aux--;
}
arr[aux + 1] = temp;
}
return arr;
}