/// <summary> /// Add if the input T is not present in the minheap map /// and if the input T is present then change the priority according the the /// priority of the input /// </summary> /// <param name="val"></param> public void AddOrChangePriority(T val) { if (!AllEntitiesIndex.ContainsKey(val.Id)) { Insert(val); } else { ChangePriority(val, val.Id); } }
/// <summary> /// This is basically used to change the value of the array at index and /// rebalance the tree to follow the min heap property /// /// We will first check whether we are increasing the priority or decreasing it, /// If we are increasing the priority, we should percolate downwards /// if we are decreasing the priority, we should percolate upwards /// /// The running time needed for this operation is O(log(n)) /// </summary> /// <param name="newVal"></param> /// <param name="index"></param> public void ChangePriority(T newVal, int Id) { if (!AllEntitiesIndex.ContainsKey(Id)) { throw new Exception("Illegal operation"); } int index = AllEntitiesIndex[Id]; if (_arrayToStoreTree[index].CompareTo(newVal) > 0) { // We have decreased the priority // We need to percolate upwards ChangeValueAtIndex(index, newVal); while (index > 0) { int parentIndex = (int)Math.Floor((index - 1) / 2.0); if (parentIndex >= 0 && _arrayToStoreTree[parentIndex].CompareTo(_arrayToStoreTree[index]) > 0) { // We need to swap the element at index with its parent Swap(index, parentIndex); index = parentIndex; } else { // The new added value is still greater than its parent, hence break break; } } } else { //We have increased the priority // we need to percolate the changes downwards ChangeValueAtIndex(index, newVal); MinHeapify(index); } }