I am trying to learn and implement a min-heap to solve a problem: Loop that creates doubles and insert them into sorted array, in C
Basically, I start with a set of doubles, sorted from smallest to largest. Then, I generate doubles (possibly at random) and have to add the newly generated doubles to the set while keeping it sorted. Also, each time I insert a double, I remove the smallest double from the set.
(edit - The set doesn't have to be entirely sorted. The goal is to be able to look up and remove the minimum element after every insertion of a double. Keeping the set sorted was my first, naive, solution.)
Sounds like the kind of thing a min-heap was made to do.
Attempt
Since in C, array sizes are declared in advance, I have to create an array with length = maximum number of doubles I will end up with. Then, fill all the entries of this array with the value max_double.
Using the methods described here as a guide: http://opendatastructures.org/versions/edition-0.1e/ods-java/10_1_BinaryHeap_Implicit_Bi.html, I can make functions to insert and remove values into this array.
Insert: Replace the last entry (which will always be max_double) of the array with the number. Then keep swapping with the value of the parent node until the parent node's value is less than newly added value.
Remove: Replace the root node with max_double, and then compare it with its two children, swapping with the least of the children until its two children are max_double.
Question
Am I using the right approach for all these?
A heap will not make the array sorted. It simply follows the rules, meaning that in a min heap, the parent will always be smaller then his children. Unfortunately, the children do not have to be in order.
If you want to implement a heap in an array, the wiki has a great page about it.
http://en.wikipedia.org/wiki/Binary_heap
Some more explanation:
Insert : Add the element to the end of the array (no replacing!) Compare the element with the parent at(i-1/2) if the order is correct stop. Otherwise swap and do step 2 again. (remember to update the current index)
Delete : Swap min with last element in the array Delete the last element Now going from the top, compare the root with its children, swap with the smallest, otherwise stop. Keep comparing with the children until the condition is satisfied or you don't have any other children.
For index starting at 0, the parent is at floor((i-1)/2) and children are at 2i+1 and 2i+2
One more thing, i suggest using a deque to store your doubles.