SlideShare a Scribd company logo
1 of 12
Download to read offline
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(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)
{
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
///
/// 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;
}
///
/// 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];
_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)
{
_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;
}
}
#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; }
}
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();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
}

More Related Content

Similar to For problems 3 and 4, consider the following functions that implemen.pdf

In this lab, you will be given a simple code for a min Heap, and you.pdf
In this lab, you will be given a simple code for a min Heap, and you.pdfIn this lab, you will be given a simple code for a min Heap, and you.pdf
In this lab, you will be given a simple code for a min Heap, and you.pdfcharanjit1717
 
Removal Of Recursion
Removal Of RecursionRemoval Of Recursion
Removal Of RecursionRicha Sharma
 
Immutability and pure functions
Immutability and pure functionsImmutability and pure functions
Immutability and pure functionssparkfabrik
 
Nevyn — Promise, It's Async! Swift Language User Group Lightning Talk 2015-09-24
Nevyn — Promise, It's Async! Swift Language User Group Lightning Talk 2015-09-24Nevyn — Promise, It's Async! Swift Language User Group Lightning Talk 2015-09-24
Nevyn — Promise, It's Async! Swift Language User Group Lightning Talk 2015-09-24Joachim Bengtsson
 
Complete the classes shown below 1. The MinHeap Class Write necessa.pdf
Complete the classes shown below 1. The MinHeap Class Write necessa.pdfComplete the classes shown below 1. The MinHeap Class Write necessa.pdf
Complete the classes shown below 1. The MinHeap Class Write necessa.pdfamericanopticalscbe
 
9. DBMS Experiment Laboratory PresentationPPT
9. DBMS Experiment Laboratory PresentationPPT9. DBMS Experiment Laboratory PresentationPPT
9. DBMS Experiment Laboratory PresentationPPTTheVerse1
 
Fundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptxFundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptxChandrakantDivate1
 
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxPROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxamrit47
 
Rntb20200805
Rntb20200805Rntb20200805
Rntb20200805t k
 
Moo at App::Math::Trainer
Moo at App::Math::TrainerMoo at App::Math::Trainer
Moo at App::Math::TrainerJens Rehsack
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8RichardWarburton
 
Higher Order Components and Render Props
Higher Order Components and Render PropsHigher Order Components and Render Props
Higher Order Components and Render PropsNitish Phanse
 
In java , I want you to implement a Data Structure known as a Doubly.pdf
In java , I want you to implement a Data Structure known as a Doubly.pdfIn java , I want you to implement a Data Structure known as a Doubly.pdf
In java , I want you to implement a Data Structure known as a Doubly.pdfaromalcom
 
Files that you must write and turn in Please do not turn in.pdf
Files that you must write and turn in Please do not turn in.pdfFiles that you must write and turn in Please do not turn in.pdf
Files that you must write and turn in Please do not turn in.pdfactocomputer
 
This is to test a balanced tree. I need help testing an unbalanced t.pdf
This is to test a balanced tree. I need help testing an unbalanced t.pdfThis is to test a balanced tree. I need help testing an unbalanced t.pdf
This is to test a balanced tree. I need help testing an unbalanced t.pdfakaluza07
 

Similar to For problems 3 and 4, consider the following functions that implemen.pdf (20)

In this lab, you will be given a simple code for a min Heap, and you.pdf
In this lab, you will be given a simple code for a min Heap, and you.pdfIn this lab, you will be given a simple code for a min Heap, and you.pdf
In this lab, you will be given a simple code for a min Heap, and you.pdf
 
Removal Of Recursion
Removal Of RecursionRemoval Of Recursion
Removal Of Recursion
 
Immutability and pure functions
Immutability and pure functionsImmutability and pure functions
Immutability and pure functions
 
Nevyn — Promise, It's Async! Swift Language User Group Lightning Talk 2015-09-24
Nevyn — Promise, It's Async! Swift Language User Group Lightning Talk 2015-09-24Nevyn — Promise, It's Async! Swift Language User Group Lightning Talk 2015-09-24
Nevyn — Promise, It's Async! Swift Language User Group Lightning Talk 2015-09-24
 
C++ aptitude
C++ aptitudeC++ aptitude
C++ aptitude
 
Complete the classes shown below 1. The MinHeap Class Write necessa.pdf
Complete the classes shown below 1. The MinHeap Class Write necessa.pdfComplete the classes shown below 1. The MinHeap Class Write necessa.pdf
Complete the classes shown below 1. The MinHeap Class Write necessa.pdf
 
9. DBMS Experiment Laboratory PresentationPPT
9. DBMS Experiment Laboratory PresentationPPT9. DBMS Experiment Laboratory PresentationPPT
9. DBMS Experiment Laboratory PresentationPPT
 
Fundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptxFundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptx
 
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxPROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
 
Heaps
HeapsHeaps
Heaps
 
Function in c
Function in cFunction in c
Function in c
 
User defined functions.1
User defined functions.1User defined functions.1
User defined functions.1
 
Rntb20200805
Rntb20200805Rntb20200805
Rntb20200805
 
Moo at App::Math::Trainer
Moo at App::Math::TrainerMoo at App::Math::Trainer
Moo at App::Math::Trainer
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8
 
Function in c
Function in cFunction in c
Function in c
 
Higher Order Components and Render Props
Higher Order Components and Render PropsHigher Order Components and Render Props
Higher Order Components and Render Props
 
In java , I want you to implement a Data Structure known as a Doubly.pdf
In java , I want you to implement a Data Structure known as a Doubly.pdfIn java , I want you to implement a Data Structure known as a Doubly.pdf
In java , I want you to implement a Data Structure known as a Doubly.pdf
 
Files that you must write and turn in Please do not turn in.pdf
Files that you must write and turn in Please do not turn in.pdfFiles that you must write and turn in Please do not turn in.pdf
Files that you must write and turn in Please do not turn in.pdf
 
This is to test a balanced tree. I need help testing an unbalanced t.pdf
This is to test a balanced tree. I need help testing an unbalanced t.pdfThis is to test a balanced tree. I need help testing an unbalanced t.pdf
This is to test a balanced tree. I need help testing an unbalanced t.pdf
 

More from anjandavid

I am exploring the basic components of advanced broadband networks..pdf
I am exploring the basic components of advanced broadband networks..pdfI am exploring the basic components of advanced broadband networks..pdf
I am exploring the basic components of advanced broadband networks..pdfanjandavid
 
How many different instances of the ls command are installed on .pdf
How many different instances of the ls command are installed on .pdfHow many different instances of the ls command are installed on .pdf
How many different instances of the ls command are installed on .pdfanjandavid
 
How are the Allen Bradley SLC 500 program files organizedSolutio.pdf
How are the Allen Bradley SLC 500 program files organizedSolutio.pdfHow are the Allen Bradley SLC 500 program files organizedSolutio.pdf
How are the Allen Bradley SLC 500 program files organizedSolutio.pdfanjandavid
 
Hi, I need help please, this is about KaseyaWich o the following .pdf
Hi, I need help please, this is about KaseyaWich o the following .pdfHi, I need help please, this is about KaseyaWich o the following .pdf
Hi, I need help please, this is about KaseyaWich o the following .pdfanjandavid
 
How did WWI and its aftermath provide African Americans with opportu.pdf
How did WWI and its aftermath provide African Americans with opportu.pdfHow did WWI and its aftermath provide African Americans with opportu.pdf
How did WWI and its aftermath provide African Americans with opportu.pdfanjandavid
 
Give an example of a system. What are the Components, Attributes,.pdf
Give an example of a system. What are the Components, Attributes,.pdfGive an example of a system. What are the Components, Attributes,.pdf
Give an example of a system. What are the Components, Attributes,.pdfanjandavid
 
Discuss the attribution process and attribution errorsSolution.pdf
Discuss the attribution process and attribution errorsSolution.pdfDiscuss the attribution process and attribution errorsSolution.pdf
Discuss the attribution process and attribution errorsSolution.pdfanjandavid
 
E, an individual, received $40,000 of non-eligible dividends from Ca.pdf
E, an individual, received $40,000 of non-eligible dividends from Ca.pdfE, an individual, received $40,000 of non-eligible dividends from Ca.pdf
E, an individual, received $40,000 of non-eligible dividends from Ca.pdfanjandavid
 
Describe one (1) example in which laws granting freedom of the press.pdf
Describe one (1) example in which laws granting freedom of the press.pdfDescribe one (1) example in which laws granting freedom of the press.pdf
Describe one (1) example in which laws granting freedom of the press.pdfanjandavid
 
Briefly discuss 3–5 key trends in the modern health care operation.pdf
Briefly discuss 3–5 key trends in the modern health care operation.pdfBriefly discuss 3–5 key trends in the modern health care operation.pdf
Briefly discuss 3–5 key trends in the modern health care operation.pdfanjandavid
 
A student obtained the following data Mass of water in calorimeter 3.pdf
A student obtained the following data Mass of water in calorimeter 3.pdfA student obtained the following data Mass of water in calorimeter 3.pdf
A student obtained the following data Mass of water in calorimeter 3.pdfanjandavid
 
All answers must be in your own words.What is importance of the Wa.pdf
All answers must be in your own words.What is importance of the Wa.pdfAll answers must be in your own words.What is importance of the Wa.pdf
All answers must be in your own words.What is importance of the Wa.pdfanjandavid
 
Can someone please fix my code for a hashtable frequencey counter I.pdf
Can someone please fix my code for a hashtable frequencey counter I.pdfCan someone please fix my code for a hashtable frequencey counter I.pdf
Can someone please fix my code for a hashtable frequencey counter I.pdfanjandavid
 
A polycationic mRNA contains two or more promoter sequences. True Fal.pdf
A polycationic mRNA contains two or more promoter sequences. True Fal.pdfA polycationic mRNA contains two or more promoter sequences. True Fal.pdf
A polycationic mRNA contains two or more promoter sequences. True Fal.pdfanjandavid
 
Why are electrons shared in molecular compoundsWhy are electron.pdf
Why are electrons shared in molecular compoundsWhy are electron.pdfWhy are electrons shared in molecular compoundsWhy are electron.pdf
Why are electrons shared in molecular compoundsWhy are electron.pdfanjandavid
 
Which of these isare true of UDPa. It provides reliability, flow-c.pdf
Which of these isare true of UDPa. It provides reliability, flow-c.pdfWhich of these isare true of UDPa. It provides reliability, flow-c.pdf
Which of these isare true of UDPa. It provides reliability, flow-c.pdfanjandavid
 
Which liquid would BaCl Which liquid would BaCl 4. Which liquid.pdf
Which liquid would BaCl Which liquid would BaCl 4. Which liquid.pdfWhich liquid would BaCl Which liquid would BaCl 4. Which liquid.pdf
Which liquid would BaCl Which liquid would BaCl 4. Which liquid.pdfanjandavid
 
What is employee involvement What are some of the benefits of invol.pdf
What is employee involvement What are some of the benefits of invol.pdfWhat is employee involvement What are some of the benefits of invol.pdf
What is employee involvement What are some of the benefits of invol.pdfanjandavid
 
What are the pros and cons of technological leader versus technologi.pdf
What are the pros and cons of technological leader versus technologi.pdfWhat are the pros and cons of technological leader versus technologi.pdf
What are the pros and cons of technological leader versus technologi.pdfanjandavid
 
What are the benefits of using the Theory X and Theory Y management .pdf
What are the benefits of using the Theory X and Theory Y management .pdfWhat are the benefits of using the Theory X and Theory Y management .pdf
What are the benefits of using the Theory X and Theory Y management .pdfanjandavid
 

More from anjandavid (20)

I am exploring the basic components of advanced broadband networks..pdf
I am exploring the basic components of advanced broadband networks..pdfI am exploring the basic components of advanced broadband networks..pdf
I am exploring the basic components of advanced broadband networks..pdf
 
How many different instances of the ls command are installed on .pdf
How many different instances of the ls command are installed on .pdfHow many different instances of the ls command are installed on .pdf
How many different instances of the ls command are installed on .pdf
 
How are the Allen Bradley SLC 500 program files organizedSolutio.pdf
How are the Allen Bradley SLC 500 program files organizedSolutio.pdfHow are the Allen Bradley SLC 500 program files organizedSolutio.pdf
How are the Allen Bradley SLC 500 program files organizedSolutio.pdf
 
Hi, I need help please, this is about KaseyaWich o the following .pdf
Hi, I need help please, this is about KaseyaWich o the following .pdfHi, I need help please, this is about KaseyaWich o the following .pdf
Hi, I need help please, this is about KaseyaWich o the following .pdf
 
How did WWI and its aftermath provide African Americans with opportu.pdf
How did WWI and its aftermath provide African Americans with opportu.pdfHow did WWI and its aftermath provide African Americans with opportu.pdf
How did WWI and its aftermath provide African Americans with opportu.pdf
 
Give an example of a system. What are the Components, Attributes,.pdf
Give an example of a system. What are the Components, Attributes,.pdfGive an example of a system. What are the Components, Attributes,.pdf
Give an example of a system. What are the Components, Attributes,.pdf
 
Discuss the attribution process and attribution errorsSolution.pdf
Discuss the attribution process and attribution errorsSolution.pdfDiscuss the attribution process and attribution errorsSolution.pdf
Discuss the attribution process and attribution errorsSolution.pdf
 
E, an individual, received $40,000 of non-eligible dividends from Ca.pdf
E, an individual, received $40,000 of non-eligible dividends from Ca.pdfE, an individual, received $40,000 of non-eligible dividends from Ca.pdf
E, an individual, received $40,000 of non-eligible dividends from Ca.pdf
 
Describe one (1) example in which laws granting freedom of the press.pdf
Describe one (1) example in which laws granting freedom of the press.pdfDescribe one (1) example in which laws granting freedom of the press.pdf
Describe one (1) example in which laws granting freedom of the press.pdf
 
Briefly discuss 3–5 key trends in the modern health care operation.pdf
Briefly discuss 3–5 key trends in the modern health care operation.pdfBriefly discuss 3–5 key trends in the modern health care operation.pdf
Briefly discuss 3–5 key trends in the modern health care operation.pdf
 
A student obtained the following data Mass of water in calorimeter 3.pdf
A student obtained the following data Mass of water in calorimeter 3.pdfA student obtained the following data Mass of water in calorimeter 3.pdf
A student obtained the following data Mass of water in calorimeter 3.pdf
 
All answers must be in your own words.What is importance of the Wa.pdf
All answers must be in your own words.What is importance of the Wa.pdfAll answers must be in your own words.What is importance of the Wa.pdf
All answers must be in your own words.What is importance of the Wa.pdf
 
Can someone please fix my code for a hashtable frequencey counter I.pdf
Can someone please fix my code for a hashtable frequencey counter I.pdfCan someone please fix my code for a hashtable frequencey counter I.pdf
Can someone please fix my code for a hashtable frequencey counter I.pdf
 
A polycationic mRNA contains two or more promoter sequences. True Fal.pdf
A polycationic mRNA contains two or more promoter sequences. True Fal.pdfA polycationic mRNA contains two or more promoter sequences. True Fal.pdf
A polycationic mRNA contains two or more promoter sequences. True Fal.pdf
 
Why are electrons shared in molecular compoundsWhy are electron.pdf
Why are electrons shared in molecular compoundsWhy are electron.pdfWhy are electrons shared in molecular compoundsWhy are electron.pdf
Why are electrons shared in molecular compoundsWhy are electron.pdf
 
Which of these isare true of UDPa. It provides reliability, flow-c.pdf
Which of these isare true of UDPa. It provides reliability, flow-c.pdfWhich of these isare true of UDPa. It provides reliability, flow-c.pdf
Which of these isare true of UDPa. It provides reliability, flow-c.pdf
 
Which liquid would BaCl Which liquid would BaCl 4. Which liquid.pdf
Which liquid would BaCl Which liquid would BaCl 4. Which liquid.pdfWhich liquid would BaCl Which liquid would BaCl 4. Which liquid.pdf
Which liquid would BaCl Which liquid would BaCl 4. Which liquid.pdf
 
What is employee involvement What are some of the benefits of invol.pdf
What is employee involvement What are some of the benefits of invol.pdfWhat is employee involvement What are some of the benefits of invol.pdf
What is employee involvement What are some of the benefits of invol.pdf
 
What are the pros and cons of technological leader versus technologi.pdf
What are the pros and cons of technological leader versus technologi.pdfWhat are the pros and cons of technological leader versus technologi.pdf
What are the pros and cons of technological leader versus technologi.pdf
 
What are the benefits of using the Theory X and Theory Y management .pdf
What are the benefits of using the Theory X and Theory Y management .pdfWhat are the benefits of using the Theory X and Theory Y management .pdf
What are the benefits of using the Theory X and Theory Y management .pdf
 

Recently uploaded

Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSAnaAcapella
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Philosophy of china and it's charactistics
Philosophy of china and it's charactisticsPhilosophy of china and it's charactistics
Philosophy of china and it's charactisticshameyhk98
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfstareducators107
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptNishitharanjan Rout
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 

Recently uploaded (20)

Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Philosophy of china and it's charactistics
Philosophy of china and it's charactisticsPhilosophy of china and it's charactistics
Philosophy of china and it's charactistics
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdf
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 

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(); }