Exemple #1
0
 void sift_down(T* array, const int start, const int end) {
   int root = start;
   while (heap_left_child(root) <= end) {
     int left_child = heap_left_child(root);
     int swap = root;
     if (array[swap] < array[left_child]) {
       swap = left_child;
     }
     int right_child = left_child + 1;
     if ((end >= right_child) && (array[swap] < array[right_child])) {
       swap = right_child;
     }
     if (root == swap) {
       return;
     } else {
       std::swap(array[root], array[swap]);
       root = swap;
     }
   }
 }  // end of sift_down
Exemple #2
0
/*
  Implemented so that end should be the length of the heap, rather
  than the index of the last element. Swap the '<' to '<=' to make
  end the index of the last element.
*/
static void sift_down(binary_heap *heap, long root, long end) {
    long l,r,swap;
    while((l = heap_left_child(root)) < end) {
        r = heap_right_child(root);
        swap = root;
        //should we swap with the left
        if(heap->cmp(heap->heap[l],heap->heap[swap])) {
            swap = l;
        }//can I make this next if and else if?
        if(r < end && heap->cmp(heap->heap[r],heap->heap[swap])) {
            swap = r;
        }
        if(swap != root) {
            SWAP(heap->heap[root],heap->heap[swap]);
            root = swap;
        } else {
            return;
        }
    }
}
Exemple #3
0
void heap_bubble_down(Heap* heap, int index) {
  if(heap_left_child_index(index) <= heap_last_index(heap)) {
    int left_compare = heap->comparator(heap_get(heap, index), heap_left_child(heap, index));
    if(1 == left_compare) {
      heap_swap(heap, index, heap_left_child_index(index));
      heap_bubble_down(heap, heap_left_child_index(index));
      return;
    } 
  }
  
  if(heap_right_child_index(index) <= heap_last_index(heap)) {
    int right_compare = heap->comparator(heap_get(heap, index), heap_right_child(heap, index));
    if(1 == right_compare) {
      heap_swap(heap, index, heap_right_child_index(index));
      heap_bubble_down(heap, heap_right_child_index(index));
      return;
    }
  }

  return;
}