Skip to content

Instantly share code, notes, and snippets.

@jmhertlein
Created October 16, 2012 20:39
Show Gist options
  • Select an option

  • Save jmhertlein/3901840 to your computer and use it in GitHub Desktop.

Select an option

Save jmhertlein/3901840 to your computer and use it in GitHub Desktop.
buildMaxHeap(data)
//Precondition: data is an ordered set that contains n elements
data.heapSize = data.length
//Loop invariant: the trees rooted at indices in the range [i,n] are max-heaps
for i=FLOOR(data.length/2) downto 1
maxHeapify(data, I)
//Postcondition: data[1] is the root of a tree that is a max-heap
mergeSort(data)
//Precondition: data is an ordered set of n elements
if data.length <= 1
return data
middle = floor(data.length/2)
foreach e in data before middle
left.add(e)
foreach e in data after or at middle
right.add(e)
left = mergeSort(left)
right = mergeSort(right)
//Postcondition: the result of merge(left,right) is a sorted
//permutation of the original n elements that were/are in data.
return merge(left,right)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment