JavaScript - 排序算法 - 堆排序

2020-10-22  本文已影响0人  ElricTang

特点:

原理:

代码实现:

parent(i) = floor((i - 1)/2)
left(i)   = 2i + 1
right(i)  = 2i + 2
// 数据结构-最大堆
let heap = [];

// utils,交换位置
function swap(index1, index2) {
    [heap[index1], heap[index2]] = [heap[index2], heap[index1]];
}

// 上浮shiftUp,维护堆的属性
function shiftUp(index) {
    let fatherIndex = Math.floor((index - 1) / 2);

    if (index !== 0 && heap[fatherIndex] < heap[index]) {
        swap(fatherIndex, index);
        shiftUp(fatherIndex);
    }
}

// 下沉shiftDown,也被称为堆化
function shiftDown(index) {
    // 判断是否比子节点小
    let leftChild = index * 2 + 1;
    let rightChild = index * 2 + 2;

    if (leftChild < heap.length && heap[index] < heap[leftChild]) {
        swap(index, leftChild);
        shiftDown(leftChild);
    }
    if (rightChild < heap.length && heap[index] < heap[rightChild]) {
        swap(index, rightChild);
        shiftDown(rightChild);
    }
}

function heapSort(arr) {
    // 建堆
    for (let i of arr) {
        heap.push(i);
        shiftUp(heap.length - 1);
    }
    let res = [];

    while (heap.length > 0) {
        swap(0, heap.length - 1);
        res.push(heap.pop());
        shiftDown(0);
    }
    return res;
}
上一篇下一篇

猜你喜欢

热点阅读