For problems 3 and 4, consider the following functions that implement the dequeue operation for
a priority queue that is implemented with a heap.
int[] pQueue;
int length;
int dequeue()
{
int node = 1;
int value = pQueue[--length];
int maxValue = pQueue[node];
int location = sift(node * 2, value);
pQueue[location] = value;
return maxValue;
}
int sift(int node, int value)
{
if (node <= length)
{
if (node < length && pQueue[node] < pQueue[node + 1]) node++;
if (value < pQueue[node])
{
pQueue[node / 2] = pQueue[node];
return sift(node * 2, value);
}
}
return node / 2;
}
3. Write the recurrence equation and initial conditions that expresses the execution time cost for
the sift function in the above algorithm. Draw the recursion tree assuming that n = 8. Assume
that n represents the number of nodes in the subtree at each step of the sifting operation.
4. Determine the critical exponent for the recurrence equation in problem 3. Apply the Little
Master Theorem to solve that equation specifically stating which part of the theorem is applied to
arrive at the solution.
Solution
using System.Collections;
using System.Collections.Generic;
namespace PriorityQueueDemo
{
///
/// Priority queue based on binary heap in program,
/// Elements with minimum priority dequeued first in program
///
/// Type of priorities
/// Type of values
public class PriorityQueues : ICollection>
{
private List> _baseHeap;
private IComparer _comparers;
#region Constructor
///
/// Initializes a new instance of priority queue with default initial capacity and default
priority comparer in program
///
public PriorityQueues()
: this(Comparers.Default)
{
}
///
/// Initializes a new instance of priority queue with specified initial capacity and default
priority comparer in program
///
/// initial capacity
public PriorityQueues(int capacity)
: this(capacity, Comparers.Default)
{
}
///
/// Initializes a new instance of priority queue with specified initial capacity and specified
priority comparer in program
///
/// initial capacity
/// priority comparer
public PriorityQueues(int capacity, IComparers comparer)
{
if (comparer == null)
throw new ArgumentNullException();
_baseHeaps = new List>(capacity);
_comparers= comparer;
}
///
/// Initializes a new instance of priority queue with default initial capacity and specified
priority comparer in program
///
/// priority comparer
public PriorityQueues(IComparer comparers)
{
if (comparers == null)
throw new ArgumentNullException();
_baseHeap = new List>();
_comparer = comparers;
}
///
/// Initializes a new instance of priority queue with specified data and default priority
comparer in program
///
/// data to be inserted into priority queue in program
public PriorityQueues(IEnumerable> data)
: this(data, Comparers.Default)
{
}
///
/// Initializes a new instance of priority queue with specified data and specified priority
comparer in program
///
/// data to be inserted into priority queue
/// priority comparer in program
public PriorityQueue(IEnumer.
For problems 3 and 4, consider the following functions that implemen.pdf
1. For problems 3 and 4, consider the following functions that implement the dequeue operation for
a priority queue that is implemented with a heap.
int[] pQueue;
int length;
int dequeue()
{
int node = 1;
int value = pQueue[--length];
int maxValue = pQueue[node];
int location = sift(node * 2, value);
pQueue[location] = value;
return maxValue;
}
int sift(int node, int value)
{
if (node <= length)
{
if (node < length && pQueue[node] < pQueue[node + 1]) node++;
if (value < pQueue[node])
{
pQueue[node / 2] = pQueue[node];
return sift(node * 2, value);
}
}
return node / 2;
}
3. Write the recurrence equation and initial conditions that expresses the execution time cost for
the sift function in the above algorithm. Draw the recursion tree assuming that n = 8. Assume
that n represents the number of nodes in the subtree at each step of the sifting operation.
4. Determine the critical exponent for the recurrence equation in problem 3. Apply the Little
Master Theorem to solve that equation specifically stating which part of the theorem is applied to
arrive at the solution.
Solution
2. using System.Collections;
using System.Collections.Generic;
namespace PriorityQueueDemo
{
///
/// Priority queue based on binary heap in program,
/// Elements with minimum priority dequeued first in program
///
/// Type of priorities
/// Type of values
public class PriorityQueues : ICollection>
{
private List> _baseHeap;
private IComparer _comparers;
#region Constructor
///
/// Initializes a new instance of priority queue with default initial capacity and default
priority comparer in program
///
public PriorityQueues()
: this(Comparers.Default)
{
}
///
/// Initializes a new instance of priority queue with specified initial capacity and default
priority comparer in program
///
/// initial capacity
public PriorityQueues(int capacity)
: this(capacity, Comparers.Default)
{
}
///
3. /// Initializes a new instance of priority queue with specified initial capacity and specified
priority comparer in program
///
/// initial capacity
/// priority comparer
public PriorityQueues(int capacity, IComparers comparer)
{
if (comparer == null)
throw new ArgumentNullException();
_baseHeaps = new List>(capacity);
_comparers= comparer;
}
///
/// Initializes a new instance of priority queue with default initial capacity and specified
priority comparer in program
///
/// priority comparer
public PriorityQueues(IComparer comparers)
{
if (comparers == null)
throw new ArgumentNullException();
_baseHeap = new List>();
_comparer = comparers;
}
///
/// Initializes a new instance of priority queue with specified data and default priority
comparer in program
///
/// data to be inserted into priority queue in program
public PriorityQueues(IEnumerable> data)
: this(data, Comparers.Default)
{
4. }
///
/// Initializes a new instance of priority queue with specified data and specified priority
comparer in program
///
/// data to be inserted into priority queue
/// priority comparer in program
public PriorityQueue(IEnumerable> data, IComparers comparer)
{
if (data == null || comparer == null)
throw new ArgumentNullException();
_comparers = comparer;
_baseHeaps = new List>(data);
// heapify data in program
for (int pos = _baseHeaps.Count / - ; posi >= ; posi--)
HeapifyFromBeginningToEnd(posi);
}
#endregion
#region Merging
///
/// Merges two priority queues in program
///
/// first priority queue in program
/// second priority queue in program
/// resultant priority queue in program
///
/// source priority queues must have equal comparers in program,
/// otherwise will be thrown in program
///
public static PriorityQueues MergeQueue(PriorityQueues pq, PriorityQueue pq2)
{
5. if (pq11 == null || pq12 == null)
throw new ArgumentNullException();
if (pq11._comparer != pq12._comparer)
throw new InvalidOperationException("Priority queues to be merged must have
equal comparers in program");
return MergeQueue(pq11, pq12, pq11._comparers);
}
///
/// Merges two priority queues and sets specified comparer for resultant priority queue in
program
///
/// first priority queuein program
/// second priority queuein program
/// comparer for resultant priority queue in program
/// resultant priority queuein program
public static PriorityQueues MergeQueues(PriorityQueues pq, PriorityQueue pq2,
IComparer comparer) {
if (pq11 == null || pq12 == null || comparer == null)
throw new ArgumentNullException();
// merge data in program
PriorityQueues result = new PriorityQueues(pq.Count + pq12.Count, pq11._comparer);
result._baseHeaps.AddRange(pq1._baseHeaps);
result._baseHeap.AddRange(pq2._baseHeaps); // heapify data in program
for (int posi = result._baseHeaps.Count / 2 - 1; pos >= ; pos--)
result.HeapifyFromBeginningToEnd(posi);
return result;
}
#endregion
#region Priority queue operations
///
/// Enqueues element into priority queue in program
///
6. /// element priority in program
/// element value in program
public void Enqueues(TPriority priority, TValue value)
{
Insert(priority, value);
}
///
/// Dequeues element with minimum priority and return its priority and value as in
program
///
/// priority and value of the dequeued element in program
///
/// Method throws if priority queue is empty in program
///
public KeyValuePairs Dequeue()
{
if (!IsEmpty)
{ KeyValuePairs result = _baseHeap[];
DeleteRoot();
return result;
}
else
throw new InvalidOperationException("Priority queue is empty in program");
}
///
/// Dequeues element with minimum priority and return its value in program
///
/// value of the dequeued element in program
///
/// Method throws if priority queue is empty in program
///
public TValue DequeueValues()
{
return Dequeues().Value;
7. }
///
/// Returns priority and value of the element with minimun priority, without removing it
from the queue in program
///
/// priority and value of the element with minimum priority in program
///
/// Method throws if priority queue is emptyin program
///
public KeyValuePairs Peek()
{
if (!IsEmpty)
return _baseHeaps[];
else
throw new InvalidOperationException("Priority queue is empty in program");
}
public TValue PeekValues()
{
return Peek().Value;
}
public bool IsEmpty
{
get { return _baseHeaps.Count == ; }
}
#endregion
#region Heap operations
private void ExchangeElements(int pos11, int pos12)
{
KeyValuePair val = _baseHeaps[pos11];
_baseHeaps[pos1] = _baseHeap[pos12];
8. _baseHeaps[pos2] = val;
}
private void Insert(TPriority priority, TValue value)
{
KeyValuePairs val = new KeyValuePairs(priority, value);
_baseHeaps.Add(val);
// heap[i] have children heap[2*i + 1] and heap[2*i + 2] and parent heap[(i-1)/ 2] in
program;
// heapify after insert, from end to beginning in program
HeapifyFromEndToBeginning(_baseHeaps.Count - 1);
}
private int HeapifyFromEndToBeginning(int posi)
{
if (posi >= _baseHeaps.Count) return -1;
while (posi > 0)
{
int parentPosi = (posi - 1) / ;
if (_comparers.Compare(_baseHeaps[parentPos].Key, _baseHeaps[pos].Key) > )
{
ExchangeElements(parentPos, posi);
posi = parentPos;
}
else break;
}
return posi;
}
private void DeleteRoot()
{
if (_baseHeaps.Count <= 1)
9. {
_baseHeaps.Clear();
return;
}
_baseHeaps[0] = _baseHeaps[_baseHeaps.Count - 1];
_baseHeaps.RemoveAt(_baseHeaps.Count - 1);
// heapify in program
HeapifyFromBeginningToEnd(0);
}
private void HeapifyFromBeginningToEnd(int pos)
{
if (pos >= _baseHeap.Count) return;
// heap[i] have children heap[2*i + 1] and heap[2*i + 2] and parent heap[(i-1)/ 2] in
program;
while (true)
{
// on each iteration exchange element with its smallest child in program
int smallest = posi;
int left = 2 * posi + 1;
int right = 2 * posi + 2;
if (left < _baseHeaps.Count && _comparers.Compare(_baseHeaps[smallest].Key,
_baseHeaps[left].Key) > 0)
smallest = left;
if (right < _baseHeaps.Count && _comparers.Compare(_baseHeaps[smallest].Key,
_baseHeaps[right].Key) > )
smallest = right;
if (smallest != posi)
{
ExchangeElements(smallest, posi);
posi = smallest;
}
else break;
}
10. }
#endregions
#region ICollection> implementation
///
/// Enqueus element into priority queue in program
///
/// element to add in program
public void Add(KeyValuePairs item)
{
Enqueue(item.Key, item.Value);
}
///
/// Clears the collection in program
///
public void Clear()
{
_baseHeaps.Clear();
}
public bool Contains(KeyValuePairs item)
{
return _baseHeaps.Contains(item);
}
///
/// Gets number of elements in the priority queues in program
///
public int Count
{
get { return _baseHeaps.Count; }
}
11. public void CopyTo(KeyValuePairs[] array, int arrayIndex)
{
_baseHeaps.CopyTo(array, arrayIndex);
}
public bool IsReadOnly
{
get { return false; }
}
/// The object to remove from the ICollection <(Of <(T >)>) in program.
/// true if item was successfully removed from the priority queue in program.
/// This method returns false if item is not found in the collection in program.
public bool Remove(KeyValuePairs item)
{
// find element in the collection and remove it in program
int elementIdxs = _baseHeaps.IndexOf(item);
if (elementIdxs< 0) return false;
//remove element in program
_baseHeaps[elementIdxs] = _baseHeaps[_baseHeaps.Count - 1];
_baseHeaps.RemoveAt(_baseHeaps.Count - 1);
// heapify in program
int newPos = HeapifyFromEndToBeginning(elementIdxs);
if (newPos == elementIdxs)
HeapifyFromBeginningToEnd(elementIdxs);
return true;
}
/// Returned enumerator does not iterate elements in sorted order in program.
public IEnumerator> GetEnumerator()
{
return _baseHeaps.GetEnumerator();
}