Skip to content

Commit

Permalink
feat(CV-0): further cleanup and simplification of API
Browse files Browse the repository at this point in the history
  • Loading branch information
daniel-jonathan committed Sep 18, 2023
1 parent 645de35 commit 8606578
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 19 deletions.
9 changes: 4 additions & 5 deletions __tests__/structures/Heap.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,17 +37,16 @@ import {
} from 'vitest'

import {
createMaxHeap,
buildMaxHeap,
heapSort,
} from '@/index'

describe('Heap', () => {
it('createMaxHeap', () => {
it('buildMaxHeap', () => {
const nodes = [ 4, 1, 3, 2, 16, 9, 10, 14, 8, 7 ]
const heap = createMaxHeap(nodes)
buildMaxHeap(nodes)

expect(heap.size).toBe(nodes.length)
expect(heap.nodes).toStrictEqual([ 16, 14, 10, 8, 7, 9, 3, 2, 4, 1 ])
expect(nodes).toStrictEqual([ 16, 14, 10, 8, 7, 9, 3, 2, 4, 1 ])
})

it('heapSort', () => {
Expand Down
17 changes: 3 additions & 14 deletions src/structures/Heap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,18 +32,12 @@

/**
* @module Heap
*
*/

import {
assert,
} from '@cosmicmind/foundationjs'

export type Heap<T> = {
nodes: T[]
size: number
}

export const heapParent = (index: number): number | never => {
assert(0 <= index, 'index must be 0 or greater')
return Math.floor((index - 1) / 2)
Expand Down Expand Up @@ -94,23 +88,18 @@ export const heapMaxHeapify = <T>(nodes: T[], size: number, index: number): void
}
}

export const createMaxHeap = <T>(nodes: T[]): Heap<T> => {
export const buildMaxHeap = <T>(nodes: T[]): void | never => {
const size = nodes.length

for (let i = Math.floor(size / 2); 0 <= i; --i) {
heapMaxHeapify(nodes, size, i)
}

return {
nodes,
size,
}
}

export const heapSort = <T>(nodes: T[]): void | never => {
const heap = createMaxHeap(nodes)
buildMaxHeap(nodes)

for (let i = heap.size - 1; 0 < i; --i) {
for (let i = nodes.length - 1; 0 < i; --i) {
heapSwapAt(nodes, 0, i)
heapMaxHeapify(nodes, i, 0)
}
Expand Down

0 comments on commit 8606578

Please sign in to comment.