Created
June 22, 2019 20:03
-
-
Save samteb/ae09a4aad19022c953bc229a1562f1e8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MaxBinaryHeap { | |
constructor () { | |
this.values = []; | |
} | |
insert (value) { | |
this.values.push(value); | |
this.bubbleUp(); | |
} | |
bubbleUp () { | |
let index = this.values.length - 1; | |
const element = this.values[index]; | |
while (index > 0) { | |
const parentIndex = Math.floor((index - 1) / 2); | |
const parent = this.values[parentIndex]; | |
if (parent >= element) break; | |
this.values[parentIndex] = element; | |
this.values[index] = parent; | |
index = parentIndex; | |
} | |
return this; | |
} | |
extractMax () { | |
const max = this.values[0]; | |
const end = this.values.pop(); | |
if (this.values.length > 0){ | |
this.values[0] = end; | |
this.sinkDown(); | |
} | |
return max; | |
} | |
sinkDown () { | |
let parentIdx = 0; | |
const parentElement = this.values[parentIdx]; | |
const length = this.values.length; | |
while (true) { | |
const leftChildIdx = 2 * parentIdx + 1; | |
const rightChildIdx = 2 * parentIdx + 2; | |
let leftChild = null; | |
let rightChild = null; | |
let swapIdx = null; | |
if (leftChildIdx < length) { | |
leftChild = this.values[leftChildIdx]; | |
if (leftChild > parentElement) { | |
swapIdx = leftChildIdx; | |
} | |
} | |
if (rightChildIdx < length) { | |
rightChild = this.values[rightChildIdx]; | |
if ( | |
(swapIdx === null && rightChild > parentElement) || | |
(swapIdx !== null && rightChild > leftChild) | |
) { | |
swapIdx = rightChildIdx; | |
} | |
} | |
if (swapIdx === null) break; | |
this.values[parentIdx] = this.values[swapIdx]; | |
this.values[swapIdx] = parentElement; | |
parentIdx = swapIdx; | |
} | |
} | |
} | |
const MaxHeapify = (values) => { | |
const maxHeap = new MaxBinaryHeap(); | |
for (const value of values) { | |
maxHeap.insert(value); | |
} | |
return maxHeap; | |
}; | |
const HeapSort = (values) => { | |
const maxHeap = MaxHeapify(values); | |
const result = []; | |
while (maxHeap.values.length) { | |
result.unshift(maxHeap.extractMax()); | |
} | |
return result; | |
}; | |
HeapSort([4,5,7,3,2,6,9,8]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment