힙 정렬은 기본적으로 비교 기반 정렬 알고리즘입니다. 개선된 선택 정렬로 생각할 수 있습니다. 해당 알고리즘과 마찬가지로 입력을 정렬된 영역과 정렬되지 않은 영역으로 나누고 대상(가장 크거나 작은) 요소를 추출하고 정렬된 영역으로 이동하여 정렬되지 않은 영역을 대화식으로 축소합니다. 지역.
예시
이에 대한 코드는 -
const constructHeap = (arr, ind) => {
let left = 2 * ind + 1;
let right = 2 * ind + 2;
let max = ind;
if (left < len && arr[left] > arr[max]) {
max = left;
}
if (right < len && arr[right] > arr[max]) {
max = right;
}
if (max != ind) {
swap(arr, ind, max);
constructHeap(arr, max);
}
}
function swap(arr, index_A, index_B) {
let temp = arr[index_A];
arr[index_A] = arr[index_B];
arr[index_B] = temp;
}
function heapSort(arr) {
len = arr.length;
for (let ind = Math.floor(len / 2); ind >= 0; ind −= 1) {
constructHeap(arr, ind);
}
for (ind = arr.length − 1; ind > 0; ind−−) {
swap(arr, 0, ind);
len−−;
constructHeap(arr, 0);
}
}
const arr = [3, 0, 2, 5, −1, 4, 1];
heapSort(arr);
console.log(arr);
var len; 출력
콘솔의 출력은 -
[ −1, 0, 1, 2, 3, 4, 5 ]