선택 정렬
const array = [7, 5, 9, 0, 3, 1, 6, 2, 4, 8];
for (let i = 0; i < array.length; i++) {
let minIndex = i;
for (let j = i + 1; j < array.length; j++) {
if (array[minIndex] > array[j]) {
minIndex = j;
}
}
const temp = array[minIndex];
array[minIndex] = array[i];
array[i] = temp;
}
console.log(array);
삽입 정렬
const array = [7, 5, 9, 0, 3, 1, 6, 2, 4, 8];
for (let i = 1; i < array.length; i++) {
for (let j = i; j > 0; j--) {
if (array[j] < array[j - 1]) {
const temp = array[j];
array[j] = array[j - 1];
array[j - 1] = temp;
} else {
break;
}
}
}
console.log(array);
퀵 정렬
const array = [7, 5, 9, 0, 3, 1, 6, 2, 4, 8];
function quickSort(array, start, end) {
if (start >= end) {
return;
}
pivot = start;
left = start;
right = end;
while (left <= right) {
while (left <= end && array[left] <= array[pivot]) {
left += 1;
}
while (right > start && array[right] >= array[pivot]) {
right -= 1;
}
if (left > right) {
const temp = array[right];
array[right] = array[pivot];
array[pivot] = temp;
} else {
const temp = array[right];
array[right] = array[left];
array[left] = temp;
}
}
quickSort(array, start, right - 1);
quickSort(array, right + 1, end);
}
quickSort(array, 0, array.length - 1);
console.log(array);
계수 정렬
const array = [7, 5, 9, 0, 3, 1, 6, 2, 9, 1, 4, 8, 0, 5, 2];
const count = new Array(Math.max(...array) + 1).fill(0);
for (let i = 0; i < array.length; i++) {
count[array[i]] += 1;
}
let result = '';
for (let i = 0; i < count.length; i++) {
for (let j = 0; j < count[i]; j++) {
result += i + ' ';
}
}
console.log(result);