internal static void Sink <T>(this T[] heap, int i, int count, IComparer <T> comparer, int shift) { int num = count + shift; while (true) { int num2 = i + shift; int num3 = 2 * i + shift; if (num3 > num) { break; } int num4 = num3 + 1; bool flag = num4 <= num; T x = heap[num2]; T t = heap[num3]; T y = flag ? heap[num4] : default(T); if (comparer.GreaterOrEqual(x, t) && (!flag || comparer.GreaterOrEqual(x, y))) { return; } int num5 = (!flag || comparer.GreaterOrEqual(t, y)) ? num3 : num4; heap.Swap(num2, num5); i = num5 - shift; } }
internal static void Sift <T>(this T[] heap, int i, IComparer <T> comparer, int shift) { while (i > 1) { int num = i / 2 + shift; int num2 = i + shift; if (comparer.GreaterOrEqual(heap[num], heap[num2])) { return; } heap.Swap(num, num2); i = num - shift; } }
protected internal void RemoveAt(int index, int shift) { var num = index + shift; Count--; Heap.Swap(num, Count); Heap[Count] = default(T); var num2 = index / 2 + shift; if (_comparer.GreaterOrEqual(Heap[num], Heap[num2])) { Heap.Sift(index, _comparer, shift); return; } Heap.Sink(index, Count, _comparer, shift); }
/// <summary> /// Removes item at given index /// </summary> /// <param name="index">1-based index of the element to remove</param> /// <param name="shift">Shift allows to compensate and work with arrays where heap starts not from the element at position 1. /// Shift -1 allows to work with 0-based heap as if it was 1-based. But the main reason for this is the CopyTo method.</param> protected internal void RemoveAt(int index, int shift) { var itemIndex = index + shift; Count--; _heap.Swap(itemIndex, Count); // last element at Count _heap[Count] = default(T); // release hold on the object // use a 1-based-heap index and then apply shift of -1 var parent = index / 2 + shift; // get parent // if new item at index is greater than it's parent then sift it up, else sink it down if (_comparer.GreaterOrEqual(_heap[itemIndex], _heap[parent])) { // provide a 1-based-heap index _heap.Sift(index, _comparer, shift); } else { // provide a 1-based-heap index _heap.Sink(index, Count, _comparer, shift); } }