SlideShare a Scribd company logo
1 of 18
Download to read offline
// PriorityQueue.cs
//
// Jim Mischel
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Mischel.Collections
{
[Serializable]
[ComVisible(false)]
public struct PriorityQueueItem
{
private TValue _value;
public TValue Value
{
get { return _value; }
}
private TPriority _priority;
public TPriority Priority
{
get { return _priority; }
}
internal PriorityQueueItem(TValue val, TPriority pri)
{
this._value = val;
this._priority = pri;
}
}
[Serializable]
[ComVisible(false)]
public class PriorityQueue : ICollection,
IEnumerable>
{
private PriorityQueueItem[] items;
private const Int32 DefaultCapacity = 16;
private Int32 capacity;
private Int32 numItems;
private Comparison compareFunc;
///
/// Initializes a new instance of the PriorityQueue class that is empty,
/// has the default initial capacity, and uses the default IComparer.
///
public PriorityQueue()
: this(DefaultCapacity, Comparer.Default)
{
}
public PriorityQueue(Int32 initialCapacity)
: this(initialCapacity, Comparer.Default)
{
}
public PriorityQueue(IComparer comparer)
: this(DefaultCapacity, comparer)
{
}
public PriorityQueue(int initialCapacity, IComparer comparer)
{
Init(initialCapacity, new Comparison(comparer.Compare));
}
public PriorityQueue(Comparison comparison)
: this(DefaultCapacity, comparison)
{
}
public PriorityQueue(int initialCapacity, Comparison comparison)
{
Init(initialCapacity, comparison);
}
private void Init(int initialCapacity, Comparison comparison)
{
numItems = 0;
compareFunc = comparison;
SetCapacity(initialCapacity);
}
public int Count
{
get { return numItems; }
}
public int Capacity
{
get { return items.Length; }
set { SetCapacity(value); }
}
private void SetCapacity(int newCapacity)
{
int newCap = newCapacity;
if (newCap < DefaultCapacity)
newCap = DefaultCapacity;
// throw exception if newCapacity < NumItems
if (newCap < numItems)
throw new ArgumentOutOfRangeException("newCapacity", "New capacity is less
than Count");
this.capacity = newCap;
if (items == null)
{
items = new PriorityQueueItem[newCap];
return;
}
// Resize the array.
Array.Resize>(ref items, newCap);
}
public void Enqueue(PriorityQueueItem newItem)
{
if (numItems == capacity)
{
// need to increase capacity
// grow by 50 percent
SetCapacity((3 * Capacity) / 2);
}
int i = numItems;
++numItems;
while ((i > 0) && (compareFunc(items[(i - 1) / 2].Priority, newItem.Priority) < 0))
{
items[i] = items[(i - 1) / 2];
i = (i - 1) / 2;
}
items[i] = newItem;
//if (!VerifyQueue())
//{
// Console.WriteLine("ERROR: Queue out of order!");
//}
}
public void Enqueue(TValue value, TPriority priority)
{
Enqueue(new PriorityQueueItem(value, priority));
}
private PriorityQueueItem RemoveAt(Int32 index)
{
PriorityQueueItem o = items[index];
--numItems;
// move the last item to fill the hole
PriorityQueueItem tmp = items[numItems];
// If you forget to clear this, you have a potential memory leak.
items[numItems] = default(PriorityQueueItem);
if (numItems > 0 && index != numItems)
{
// If the new item is greater than its parent, bubble up.
int i = index;
int parent = (i - 1) / 2;
while (compareFunc(tmp.Priority, items[parent].Priority) > 0)
{
items[i] = items[parent];
i = parent;
parent = (i - 1) / 2;
}
// if i == index, then we didn't move the item up
if (i == index)
{
// bubble down ...
while (i < (numItems) / 2)
{
int j = (2 * i) + 1;
if ((j < numItems - 1) && (compareFunc(items[j].Priority, items[j + 1].Priority) < 0))
{
++j;
}
if (compareFunc(items[j].Priority, tmp.Priority) <= 0)
{
break;
}
items[i] = items[j];
i = j;
}
}
// Be sure to store the item in its place.
items[i] = tmp;
}
//if (!VerifyQueue())
//{
// Console.WriteLine("ERROR: Queue out of order!");
//}
return o;
}
// Function to check that the queue is coherent.
public bool VerifyQueue()
{
int i = 0;
while (i < numItems / 2)
{
int leftChild = (2 * i) + 1;
int rightChild = leftChild + 1;
if (compareFunc(items[i].Priority, items[leftChild].Priority) < 0)
{
return false;
}
if (rightChild < numItems && compareFunc(items[i].Priority, items[rightChild].Priority) < 0)
{
return false;
}
++i;
}
return true;
}
public PriorityQueueItem Dequeue()
{
if (Count == 0)
throw new InvalidOperationException("The queue is empty");
return RemoveAt(0);
}
///
/// Removes the item with the specified value from the queue.
/// The passed equality comparison is used.
///
/// The item to be removed.
/// An object that implements the IEqualityComparer interface
/// for the type of item in the collection.
public void Remove(TValue item, IEqualityComparer comparer)
{
// need to find the PriorityQueueItem that has the Data value of o
for (int index = 0; index < numItems; ++index)
{
if (comparer.Equals(item, items[index].Value))
{
RemoveAt(index);
return;
}
}
throw new ApplicationException("The specified itemm is not in the queue.");
}
///
/// Removes the item with the specified value from the queue.
/// The default type comparison function is used.
///
/// The item to be removed.
public void Remove(TValue item)
{
Remove(item, EqualityComparer.Default);
}
public PriorityQueueItem Peek()
{
if (Count == 0)
throw new InvalidOperationException("The queue is empty");
return items[0];
}
// Clear
public void Clear()
{
for (int i = 0; i < numItems; ++i)
{
items[i] = default(PriorityQueueItem);
}
numItems = 0;
TrimExcess();
}
///
/// Set the capacity to the actual number of items, if the current
/// number of items is less than 90 percent of the current capacity.
///
public void TrimExcess()
{
if (numItems < (float)0.9 * capacity)
{
SetCapacity(numItems);
}
}
// Contains
public bool Contains(TValue o)
{
foreach (PriorityQueueItem x in items)
{
if (x.Value.Equals(o))
return true;
}
return false;
}
public void CopyTo(PriorityQueueItem[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException("array");
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException("arrayIndex", "arrayIndex is less than 0.");
if (array.Rank > 1)
throw new ArgumentException("array is multidimensional.");
if (numItems == 0)
return;
if (arrayIndex >= array.Length)
throw new ArgumentException("arrayIndex is equal to or greater than the length of the
array.");
if (numItems > (array.Length - arrayIndex))
throw new ArgumentException("The number of elements in the source ICollection is greater
than the available space from arrayIndex to the end of the destination array.");
for (int i = 0; i < numItems; i++)
{
array[arrayIndex + i] = items[i];
}
}
#region ICollection Members
public void CopyTo(Array array, int index)
{
this.CopyTo((PriorityQueueItem[])array, index);
}
public bool IsSynchronized
{
get { return false; }
}
public object SyncRoot
{
get { return items.SyncRoot; }
}
#endregion
#region IEnumerable> Members
public IEnumerator> GetEnumerator()
{
for (int i = 0; i < numItems; i++)
{
yield return items[i];
}
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
}
Solution
// PriorityQueue.cs
//
// Jim Mischel
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Mischel.Collections
{
[Serializable]
[ComVisible(false)]
public struct PriorityQueueItem
{
private TValue _value;
public TValue Value
{
get { return _value; }
}
private TPriority _priority;
public TPriority Priority
{
get { return _priority; }
}
internal PriorityQueueItem(TValue val, TPriority pri)
{
this._value = val;
this._priority = pri;
}
}
[Serializable]
[ComVisible(false)]
public class PriorityQueue : ICollection,
IEnumerable>
{
private PriorityQueueItem[] items;
private const Int32 DefaultCapacity = 16;
private Int32 capacity;
private Int32 numItems;
private Comparison compareFunc;
///
/// Initializes a new instance of the PriorityQueue class that is empty,
/// has the default initial capacity, and uses the default IComparer.
///
public PriorityQueue()
: this(DefaultCapacity, Comparer.Default)
{
}
public PriorityQueue(Int32 initialCapacity)
: this(initialCapacity, Comparer.Default)
{
}
public PriorityQueue(IComparer comparer)
: this(DefaultCapacity, comparer)
{
}
public PriorityQueue(int initialCapacity, IComparer comparer)
{
Init(initialCapacity, new Comparison(comparer.Compare));
}
public PriorityQueue(Comparison comparison)
: this(DefaultCapacity, comparison)
{
}
public PriorityQueue(int initialCapacity, Comparison comparison)
{
Init(initialCapacity, comparison);
}
private void Init(int initialCapacity, Comparison comparison)
{
numItems = 0;
compareFunc = comparison;
SetCapacity(initialCapacity);
}
public int Count
{
get { return numItems; }
}
public int Capacity
{
get { return items.Length; }
set { SetCapacity(value); }
}
private void SetCapacity(int newCapacity)
{
int newCap = newCapacity;
if (newCap < DefaultCapacity)
newCap = DefaultCapacity;
// throw exception if newCapacity < NumItems
if (newCap < numItems)
throw new ArgumentOutOfRangeException("newCapacity", "New capacity is less
than Count");
this.capacity = newCap;
if (items == null)
{
items = new PriorityQueueItem[newCap];
return;
}
// Resize the array.
Array.Resize>(ref items, newCap);
}
public void Enqueue(PriorityQueueItem newItem)
{
if (numItems == capacity)
{
// need to increase capacity
// grow by 50 percent
SetCapacity((3 * Capacity) / 2);
}
int i = numItems;
++numItems;
while ((i > 0) && (compareFunc(items[(i - 1) / 2].Priority, newItem.Priority) < 0))
{
items[i] = items[(i - 1) / 2];
i = (i - 1) / 2;
}
items[i] = newItem;
//if (!VerifyQueue())
//{
// Console.WriteLine("ERROR: Queue out of order!");
//}
}
public void Enqueue(TValue value, TPriority priority)
{
Enqueue(new PriorityQueueItem(value, priority));
}
private PriorityQueueItem RemoveAt(Int32 index)
{
PriorityQueueItem o = items[index];
--numItems;
// move the last item to fill the hole
PriorityQueueItem tmp = items[numItems];
// If you forget to clear this, you have a potential memory leak.
items[numItems] = default(PriorityQueueItem);
if (numItems > 0 && index != numItems)
{
// If the new item is greater than its parent, bubble up.
int i = index;
int parent = (i - 1) / 2;
while (compareFunc(tmp.Priority, items[parent].Priority) > 0)
{
items[i] = items[parent];
i = parent;
parent = (i - 1) / 2;
}
// if i == index, then we didn't move the item up
if (i == index)
{
// bubble down ...
while (i < (numItems) / 2)
{
int j = (2 * i) + 1;
if ((j < numItems - 1) && (compareFunc(items[j].Priority, items[j + 1].Priority) < 0))
{
++j;
}
if (compareFunc(items[j].Priority, tmp.Priority) <= 0)
{
break;
}
items[i] = items[j];
i = j;
}
}
// Be sure to store the item in its place.
items[i] = tmp;
}
//if (!VerifyQueue())
//{
// Console.WriteLine("ERROR: Queue out of order!");
//}
return o;
}
// Function to check that the queue is coherent.
public bool VerifyQueue()
{
int i = 0;
while (i < numItems / 2)
{
int leftChild = (2 * i) + 1;
int rightChild = leftChild + 1;
if (compareFunc(items[i].Priority, items[leftChild].Priority) < 0)
{
return false;
}
if (rightChild < numItems && compareFunc(items[i].Priority, items[rightChild].Priority) < 0)
{
return false;
}
++i;
}
return true;
}
public PriorityQueueItem Dequeue()
{
if (Count == 0)
throw new InvalidOperationException("The queue is empty");
return RemoveAt(0);
}
///
/// Removes the item with the specified value from the queue.
/// The passed equality comparison is used.
///
/// The item to be removed.
/// An object that implements the IEqualityComparer interface
/// for the type of item in the collection.
public void Remove(TValue item, IEqualityComparer comparer)
{
// need to find the PriorityQueueItem that has the Data value of o
for (int index = 0; index < numItems; ++index)
{
if (comparer.Equals(item, items[index].Value))
{
RemoveAt(index);
return;
}
}
throw new ApplicationException("The specified itemm is not in the queue.");
}
///
/// Removes the item with the specified value from the queue.
/// The default type comparison function is used.
///
/// The item to be removed.
public void Remove(TValue item)
{
Remove(item, EqualityComparer.Default);
}
public PriorityQueueItem Peek()
{
if (Count == 0)
throw new InvalidOperationException("The queue is empty");
return items[0];
}
// Clear
public void Clear()
{
for (int i = 0; i < numItems; ++i)
{
items[i] = default(PriorityQueueItem);
}
numItems = 0;
TrimExcess();
}
///
/// Set the capacity to the actual number of items, if the current
/// number of items is less than 90 percent of the current capacity.
///
public void TrimExcess()
{
if (numItems < (float)0.9 * capacity)
{
SetCapacity(numItems);
}
}
// Contains
public bool Contains(TValue o)
{
foreach (PriorityQueueItem x in items)
{
if (x.Value.Equals(o))
return true;
}
return false;
}
public void CopyTo(PriorityQueueItem[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException("array");
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException("arrayIndex", "arrayIndex is less than 0.");
if (array.Rank > 1)
throw new ArgumentException("array is multidimensional.");
if (numItems == 0)
return;
if (arrayIndex >= array.Length)
throw new ArgumentException("arrayIndex is equal to or greater than the length of the
array.");
if (numItems > (array.Length - arrayIndex))
throw new ArgumentException("The number of elements in the source ICollection is greater
than the available space from arrayIndex to the end of the destination array.");
for (int i = 0; i < numItems; i++)
{
array[arrayIndex + i] = items[i];
}
}
#region ICollection Members
public void CopyTo(Array array, int index)
{
this.CopyTo((PriorityQueueItem[])array, index);
}
public bool IsSynchronized
{
get { return false; }
}
public object SyncRoot
{
get { return items.SyncRoot; }
}
#endregion
#region IEnumerable> Members
public IEnumerator> GetEnumerator()
{
for (int i = 0; i < numItems; i++)
{
yield return items[i];
}
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
}

More Related Content

Similar to PriorityQueue.cs Jim Mischel using System; using Sy.pdf

Given the following errors and class in Java- How are these errors fix.pdf
Given the following errors and class in Java- How are these errors fix.pdfGiven the following errors and class in Java- How are these errors fix.pdf
Given the following errors and class in Java- How are these errors fix.pdfNicholasflqStewartl
 
Create a Dynamic Array container with this user interface Ge.pdf
Create a Dynamic Array container with this user interface  Ge.pdfCreate a Dynamic Array container with this user interface  Ge.pdf
Create a Dynamic Array container with this user interface Ge.pdfsktambifortune
 
public class DoubleArraySeq implements Cloneable {    Priva.pdf
public class DoubleArraySeq implements Cloneable {     Priva.pdfpublic class DoubleArraySeq implements Cloneable {     Priva.pdf
public class DoubleArraySeq implements Cloneable {    Priva.pdfannaimobiles
 
Given the following class in Java- public class ThreeTenDynArray-T- {.pdf
Given the following class in Java-  public class ThreeTenDynArray-T- {.pdfGiven the following class in Java-  public class ThreeTenDynArray-T- {.pdf
Given the following class in Java- public class ThreeTenDynArray-T- {.pdfNicholasflqStewartl
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 
JAVAneed help with public IteratorItem iterator()import java.u.pdf
JAVAneed help with public IteratorItem iterator()import java.u.pdfJAVAneed help with public IteratorItem iterator()import java.u.pdf
JAVAneed help with public IteratorItem iterator()import java.u.pdffcsondhiindia
 
package algs13;import stdlib.;import java.util.Iterator;im.docx
package algs13;import  stdlib.;import java.util.Iterator;im.docxpackage algs13;import  stdlib.;import java.util.Iterator;im.docx
package algs13;import stdlib.;import java.util.Iterator;im.docxgerardkortney
 
Infinum Android Talks #20 - DiffUtil
Infinum Android Talks #20 - DiffUtilInfinum Android Talks #20 - DiffUtil
Infinum Android Talks #20 - DiffUtilInfinum
 
(674335607) cs2309 java-lab-manual
(674335607) cs2309 java-lab-manual(674335607) cs2309 java-lab-manual
(674335607) cs2309 java-lab-manualChandrapriya Jayabal
 
F# in the enterprise
F# in the enterpriseF# in the enterprise
F# in the enterprise7sharp9
 
This file contains a complete array-based MultiSet, but not the code.pdf
This file contains a complete array-based MultiSet, but not the code.pdfThis file contains a complete array-based MultiSet, but not the code.pdf
This file contains a complete array-based MultiSet, but not the code.pdfdeepaksatrker
 
this file has a complete array-based MultiSet, but not the code need.pdf
this file has a complete array-based MultiSet, but not the code need.pdfthis file has a complete array-based MultiSet, but not the code need.pdf
this file has a complete array-based MultiSet, but not the code need.pdfflashfashioncasualwe
 
OBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .pptOBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .pptSaadAsim11
 
Build Widgets
Build WidgetsBuild Widgets
Build Widgetsscottw
 
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
Using c++Im also using a the ide editor called CodeLiteThe hea.pdfUsing c++Im also using a the ide editor called CodeLiteThe hea.pdf
Using c++Im also using a the ide editor called CodeLiteThe hea.pdffashiongallery1
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
Concurrent Collections Object In Dot Net 4
Concurrent Collections Object In Dot Net 4Concurrent Collections Object In Dot Net 4
Concurrent Collections Object In Dot Net 4Neeraj Kaushik
 
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
 

Similar to PriorityQueue.cs Jim Mischel using System; using Sy.pdf (20)

Given the following errors and class in Java- How are these errors fix.pdf
Given the following errors and class in Java- How are these errors fix.pdfGiven the following errors and class in Java- How are these errors fix.pdf
Given the following errors and class in Java- How are these errors fix.pdf
 
Create a Dynamic Array container with this user interface Ge.pdf
Create a Dynamic Array container with this user interface  Ge.pdfCreate a Dynamic Array container with this user interface  Ge.pdf
Create a Dynamic Array container with this user interface Ge.pdf
 
public class DoubleArraySeq implements Cloneable {    Priva.pdf
public class DoubleArraySeq implements Cloneable {     Priva.pdfpublic class DoubleArraySeq implements Cloneable {     Priva.pdf
public class DoubleArraySeq implements Cloneable {    Priva.pdf
 
Given the following class in Java- public class ThreeTenDynArray-T- {.pdf
Given the following class in Java-  public class ThreeTenDynArray-T- {.pdfGiven the following class in Java-  public class ThreeTenDynArray-T- {.pdf
Given the following class in Java- public class ThreeTenDynArray-T- {.pdf
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
JAVAneed help with public IteratorItem iterator()import java.u.pdf
JAVAneed help with public IteratorItem iterator()import java.u.pdfJAVAneed help with public IteratorItem iterator()import java.u.pdf
JAVAneed help with public IteratorItem iterator()import java.u.pdf
 
package algs13;import stdlib.;import java.util.Iterator;im.docx
package algs13;import  stdlib.;import java.util.Iterator;im.docxpackage algs13;import  stdlib.;import java.util.Iterator;im.docx
package algs13;import stdlib.;import java.util.Iterator;im.docx
 
Infinum Android Talks #20 - DiffUtil
Infinum Android Talks #20 - DiffUtilInfinum Android Talks #20 - DiffUtil
Infinum Android Talks #20 - DiffUtil
 
(674335607) cs2309 java-lab-manual
(674335607) cs2309 java-lab-manual(674335607) cs2309 java-lab-manual
(674335607) cs2309 java-lab-manual
 
F# in the enterprise
F# in the enterpriseF# in the enterprise
F# in the enterprise
 
This file contains a complete array-based MultiSet, but not the code.pdf
This file contains a complete array-based MultiSet, but not the code.pdfThis file contains a complete array-based MultiSet, but not the code.pdf
This file contains a complete array-based MultiSet, but not the code.pdf
 
this file has a complete array-based MultiSet, but not the code need.pdf
this file has a complete array-based MultiSet, but not the code need.pdfthis file has a complete array-based MultiSet, but not the code need.pdf
this file has a complete array-based MultiSet, but not the code need.pdf
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
OBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .pptOBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .ppt
 
Build Widgets
Build WidgetsBuild Widgets
Build Widgets
 
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
Using c++Im also using a the ide editor called CodeLiteThe hea.pdfUsing c++Im also using a the ide editor called CodeLiteThe hea.pdf
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Concurrent Collections Object In Dot Net 4
Concurrent Collections Object In Dot Net 4Concurrent Collections Object In Dot Net 4
Concurrent Collections Object In Dot Net 4
 
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
 
Thread
ThreadThread
Thread
 

More from rajat630669

the balanced equations are H3PO4(aq) + 3[NaOH](.pdf
                     the balanced equations are  H3PO4(aq) + 3[NaOH](.pdf                     the balanced equations are  H3PO4(aq) + 3[NaOH](.pdf
the balanced equations are H3PO4(aq) + 3[NaOH](.pdfrajat630669
 
Molecular wt. of NaOH = 40 No. of moles of NaOH =.pdf
                     Molecular wt. of NaOH = 40 No. of moles of NaOH =.pdf                     Molecular wt. of NaOH = 40 No. of moles of NaOH =.pdf
Molecular wt. of NaOH = 40 No. of moles of NaOH =.pdfrajat630669
 
images are not visible. post the question again .pdf
                     images are not visible. post the question again  .pdf                     images are not visible. post the question again  .pdf
images are not visible. post the question again .pdfrajat630669
 
VSEPR is easy if you follow the right steps. 1. .pdf
                     VSEPR is easy if you follow the right steps.  1. .pdf                     VSEPR is easy if you follow the right steps.  1. .pdf
VSEPR is easy if you follow the right steps. 1. .pdfrajat630669
 
This is quite a broad question. I will try to acc.pdf
                     This is quite a broad question. I will try to acc.pdf                     This is quite a broad question. I will try to acc.pdf
This is quite a broad question. I will try to acc.pdfrajat630669
 
}public staatic boolean isValidElement(String token){public vo.pdf
}public staatic boolean isValidElement(String token){public vo.pdf}public staatic boolean isValidElement(String token){public vo.pdf
}public staatic boolean isValidElement(String token){public vo.pdfrajat630669
 
y=41.2xSolutiony=41.2x.pdf
y=41.2xSolutiony=41.2x.pdfy=41.2xSolutiony=41.2x.pdf
y=41.2xSolutiony=41.2x.pdfrajat630669
 
What is an example of big data either from your personal experience .pdf
What is an example of big data either from your personal experience .pdfWhat is an example of big data either from your personal experience .pdf
What is an example of big data either from your personal experience .pdfrajat630669
 
S-Se=S with 3 lone pairs on the first S, 1 lone.pdf
                     S-Se=S with 3 lone pairs on the first S,   1 lone.pdf                     S-Se=S with 3 lone pairs on the first S,   1 lone.pdf
S-Se=S with 3 lone pairs on the first S, 1 lone.pdfrajat630669
 
The sample program for above series in JAVA will be like belowimpo.pdf
The sample program for above series in JAVA will be like belowimpo.pdfThe sample program for above series in JAVA will be like belowimpo.pdf
The sample program for above series in JAVA will be like belowimpo.pdfrajat630669
 
The formula for calculating Alveolar ventilation is as followsAlv.pdf
The formula for calculating Alveolar ventilation is as followsAlv.pdfThe formula for calculating Alveolar ventilation is as followsAlv.pdf
The formula for calculating Alveolar ventilation is as followsAlv.pdfrajat630669
 
D. This element can only have a -2 oxidation stat.pdf
                     D. This element can only have a -2 oxidation stat.pdf                     D. This element can only have a -2 oxidation stat.pdf
D. This element can only have a -2 oxidation stat.pdfrajat630669
 
solAn object will allocated statically when that object is needed.pdf
solAn object will allocated statically when that object is needed.pdfsolAn object will allocated statically when that object is needed.pdf
solAn object will allocated statically when that object is needed.pdfrajat630669
 
P = 12SolutionP = 12.pdf
P = 12SolutionP = 12.pdfP = 12SolutionP = 12.pdf
P = 12SolutionP = 12.pdfrajat630669
 
carbon moves by A. interstitial diffusion So.pdf
                     carbon moves by A. interstitial diffusion So.pdf                     carbon moves by A. interstitial diffusion So.pdf
carbon moves by A. interstitial diffusion So.pdfrajat630669
 
NH4Cl = acid NaOH = base They react 11 Leftover = 0.26-0..pdf
NH4Cl = acid NaOH = base They react 11 Leftover = 0.26-0..pdfNH4Cl = acid NaOH = base They react 11 Leftover = 0.26-0..pdf
NH4Cl = acid NaOH = base They react 11 Leftover = 0.26-0..pdfrajat630669
 
D is the transition represent!! Solution .pdf
                     D is the transition represent!!  Solution    .pdf                     D is the transition represent!!  Solution    .pdf
D is the transition represent!! Solution .pdfrajat630669
 
CO2 is non polar because C has no lone pairs, so .pdf
                     CO2 is non polar because C has no lone pairs, so .pdf                     CO2 is non polar because C has no lone pairs, so .pdf
CO2 is non polar because C has no lone pairs, so .pdfrajat630669
 
As more halide ions are added, it loses its color.pdf
                     As more halide ions are added, it loses its color.pdf                     As more halide ions are added, it loses its color.pdf
As more halide ions are added, it loses its color.pdfrajat630669
 
AppointmentDemo.javaimport java.util.Scanner;    Demonstrat.pdf
AppointmentDemo.javaimport java.util.Scanner;    Demonstrat.pdfAppointmentDemo.javaimport java.util.Scanner;    Demonstrat.pdf
AppointmentDemo.javaimport java.util.Scanner;    Demonstrat.pdfrajat630669
 

More from rajat630669 (20)

the balanced equations are H3PO4(aq) + 3[NaOH](.pdf
                     the balanced equations are  H3PO4(aq) + 3[NaOH](.pdf                     the balanced equations are  H3PO4(aq) + 3[NaOH](.pdf
the balanced equations are H3PO4(aq) + 3[NaOH](.pdf
 
Molecular wt. of NaOH = 40 No. of moles of NaOH =.pdf
                     Molecular wt. of NaOH = 40 No. of moles of NaOH =.pdf                     Molecular wt. of NaOH = 40 No. of moles of NaOH =.pdf
Molecular wt. of NaOH = 40 No. of moles of NaOH =.pdf
 
images are not visible. post the question again .pdf
                     images are not visible. post the question again  .pdf                     images are not visible. post the question again  .pdf
images are not visible. post the question again .pdf
 
VSEPR is easy if you follow the right steps. 1. .pdf
                     VSEPR is easy if you follow the right steps.  1. .pdf                     VSEPR is easy if you follow the right steps.  1. .pdf
VSEPR is easy if you follow the right steps. 1. .pdf
 
This is quite a broad question. I will try to acc.pdf
                     This is quite a broad question. I will try to acc.pdf                     This is quite a broad question. I will try to acc.pdf
This is quite a broad question. I will try to acc.pdf
 
}public staatic boolean isValidElement(String token){public vo.pdf
}public staatic boolean isValidElement(String token){public vo.pdf}public staatic boolean isValidElement(String token){public vo.pdf
}public staatic boolean isValidElement(String token){public vo.pdf
 
y=41.2xSolutiony=41.2x.pdf
y=41.2xSolutiony=41.2x.pdfy=41.2xSolutiony=41.2x.pdf
y=41.2xSolutiony=41.2x.pdf
 
What is an example of big data either from your personal experience .pdf
What is an example of big data either from your personal experience .pdfWhat is an example of big data either from your personal experience .pdf
What is an example of big data either from your personal experience .pdf
 
S-Se=S with 3 lone pairs on the first S, 1 lone.pdf
                     S-Se=S with 3 lone pairs on the first S,   1 lone.pdf                     S-Se=S with 3 lone pairs on the first S,   1 lone.pdf
S-Se=S with 3 lone pairs on the first S, 1 lone.pdf
 
The sample program for above series in JAVA will be like belowimpo.pdf
The sample program for above series in JAVA will be like belowimpo.pdfThe sample program for above series in JAVA will be like belowimpo.pdf
The sample program for above series in JAVA will be like belowimpo.pdf
 
The formula for calculating Alveolar ventilation is as followsAlv.pdf
The formula for calculating Alveolar ventilation is as followsAlv.pdfThe formula for calculating Alveolar ventilation is as followsAlv.pdf
The formula for calculating Alveolar ventilation is as followsAlv.pdf
 
D. This element can only have a -2 oxidation stat.pdf
                     D. This element can only have a -2 oxidation stat.pdf                     D. This element can only have a -2 oxidation stat.pdf
D. This element can only have a -2 oxidation stat.pdf
 
solAn object will allocated statically when that object is needed.pdf
solAn object will allocated statically when that object is needed.pdfsolAn object will allocated statically when that object is needed.pdf
solAn object will allocated statically when that object is needed.pdf
 
P = 12SolutionP = 12.pdf
P = 12SolutionP = 12.pdfP = 12SolutionP = 12.pdf
P = 12SolutionP = 12.pdf
 
carbon moves by A. interstitial diffusion So.pdf
                     carbon moves by A. interstitial diffusion So.pdf                     carbon moves by A. interstitial diffusion So.pdf
carbon moves by A. interstitial diffusion So.pdf
 
NH4Cl = acid NaOH = base They react 11 Leftover = 0.26-0..pdf
NH4Cl = acid NaOH = base They react 11 Leftover = 0.26-0..pdfNH4Cl = acid NaOH = base They react 11 Leftover = 0.26-0..pdf
NH4Cl = acid NaOH = base They react 11 Leftover = 0.26-0..pdf
 
D is the transition represent!! Solution .pdf
                     D is the transition represent!!  Solution    .pdf                     D is the transition represent!!  Solution    .pdf
D is the transition represent!! Solution .pdf
 
CO2 is non polar because C has no lone pairs, so .pdf
                     CO2 is non polar because C has no lone pairs, so .pdf                     CO2 is non polar because C has no lone pairs, so .pdf
CO2 is non polar because C has no lone pairs, so .pdf
 
As more halide ions are added, it loses its color.pdf
                     As more halide ions are added, it loses its color.pdf                     As more halide ions are added, it loses its color.pdf
As more halide ions are added, it loses its color.pdf
 
AppointmentDemo.javaimport java.util.Scanner;    Demonstrat.pdf
AppointmentDemo.javaimport java.util.Scanner;    Demonstrat.pdfAppointmentDemo.javaimport java.util.Scanner;    Demonstrat.pdf
AppointmentDemo.javaimport java.util.Scanner;    Demonstrat.pdf
 

Recently uploaded

18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 

Recently uploaded (20)

18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 

PriorityQueue.cs Jim Mischel using System; using Sy.pdf

  • 1. // PriorityQueue.cs // // Jim Mischel using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; namespace Mischel.Collections { [Serializable] [ComVisible(false)] public struct PriorityQueueItem { private TValue _value; public TValue Value { get { return _value; } } private TPriority _priority; public TPriority Priority { get { return _priority; } } internal PriorityQueueItem(TValue val, TPriority pri) { this._value = val; this._priority = pri; } } [Serializable] [ComVisible(false)] public class PriorityQueue : ICollection, IEnumerable> { private PriorityQueueItem[] items;
  • 2. private const Int32 DefaultCapacity = 16; private Int32 capacity; private Int32 numItems; private Comparison compareFunc; /// /// Initializes a new instance of the PriorityQueue class that is empty, /// has the default initial capacity, and uses the default IComparer. /// public PriorityQueue() : this(DefaultCapacity, Comparer.Default) { } public PriorityQueue(Int32 initialCapacity) : this(initialCapacity, Comparer.Default) { } public PriorityQueue(IComparer comparer) : this(DefaultCapacity, comparer) { } public PriorityQueue(int initialCapacity, IComparer comparer) { Init(initialCapacity, new Comparison(comparer.Compare)); } public PriorityQueue(Comparison comparison) : this(DefaultCapacity, comparison) { } public PriorityQueue(int initialCapacity, Comparison comparison) { Init(initialCapacity, comparison); } private void Init(int initialCapacity, Comparison comparison) { numItems = 0; compareFunc = comparison;
  • 3. SetCapacity(initialCapacity); } public int Count { get { return numItems; } } public int Capacity { get { return items.Length; } set { SetCapacity(value); } } private void SetCapacity(int newCapacity) { int newCap = newCapacity; if (newCap < DefaultCapacity) newCap = DefaultCapacity; // throw exception if newCapacity < NumItems if (newCap < numItems) throw new ArgumentOutOfRangeException("newCapacity", "New capacity is less than Count"); this.capacity = newCap; if (items == null) { items = new PriorityQueueItem[newCap]; return; } // Resize the array. Array.Resize>(ref items, newCap); } public void Enqueue(PriorityQueueItem newItem) { if (numItems == capacity) { // need to increase capacity // grow by 50 percent SetCapacity((3 * Capacity) / 2);
  • 4. } int i = numItems; ++numItems; while ((i > 0) && (compareFunc(items[(i - 1) / 2].Priority, newItem.Priority) < 0)) { items[i] = items[(i - 1) / 2]; i = (i - 1) / 2; } items[i] = newItem; //if (!VerifyQueue()) //{ // Console.WriteLine("ERROR: Queue out of order!"); //} } public void Enqueue(TValue value, TPriority priority) { Enqueue(new PriorityQueueItem(value, priority)); } private PriorityQueueItem RemoveAt(Int32 index) { PriorityQueueItem o = items[index]; --numItems; // move the last item to fill the hole PriorityQueueItem tmp = items[numItems]; // If you forget to clear this, you have a potential memory leak. items[numItems] = default(PriorityQueueItem); if (numItems > 0 && index != numItems) { // If the new item is greater than its parent, bubble up. int i = index; int parent = (i - 1) / 2; while (compareFunc(tmp.Priority, items[parent].Priority) > 0) { items[i] = items[parent]; i = parent; parent = (i - 1) / 2;
  • 5. } // if i == index, then we didn't move the item up if (i == index) { // bubble down ... while (i < (numItems) / 2) { int j = (2 * i) + 1; if ((j < numItems - 1) && (compareFunc(items[j].Priority, items[j + 1].Priority) < 0)) { ++j; } if (compareFunc(items[j].Priority, tmp.Priority) <= 0) { break; } items[i] = items[j]; i = j; } } // Be sure to store the item in its place. items[i] = tmp; } //if (!VerifyQueue()) //{ // Console.WriteLine("ERROR: Queue out of order!"); //} return o; } // Function to check that the queue is coherent. public bool VerifyQueue() { int i = 0; while (i < numItems / 2) { int leftChild = (2 * i) + 1;
  • 6. int rightChild = leftChild + 1; if (compareFunc(items[i].Priority, items[leftChild].Priority) < 0) { return false; } if (rightChild < numItems && compareFunc(items[i].Priority, items[rightChild].Priority) < 0) { return false; } ++i; } return true; } public PriorityQueueItem Dequeue() { if (Count == 0) throw new InvalidOperationException("The queue is empty"); return RemoveAt(0); } /// /// Removes the item with the specified value from the queue. /// The passed equality comparison is used. /// /// The item to be removed. /// An object that implements the IEqualityComparer interface /// for the type of item in the collection. public void Remove(TValue item, IEqualityComparer comparer) { // need to find the PriorityQueueItem that has the Data value of o for (int index = 0; index < numItems; ++index) { if (comparer.Equals(item, items[index].Value)) { RemoveAt(index); return; }
  • 7. } throw new ApplicationException("The specified itemm is not in the queue."); } /// /// Removes the item with the specified value from the queue. /// The default type comparison function is used. /// /// The item to be removed. public void Remove(TValue item) { Remove(item, EqualityComparer.Default); } public PriorityQueueItem Peek() { if (Count == 0) throw new InvalidOperationException("The queue is empty"); return items[0]; } // Clear public void Clear() { for (int i = 0; i < numItems; ++i) { items[i] = default(PriorityQueueItem); } numItems = 0; TrimExcess(); } /// /// Set the capacity to the actual number of items, if the current /// number of items is less than 90 percent of the current capacity. /// public void TrimExcess() { if (numItems < (float)0.9 * capacity) {
  • 8. SetCapacity(numItems); } } // Contains public bool Contains(TValue o) { foreach (PriorityQueueItem x in items) { if (x.Value.Equals(o)) return true; } return false; } public void CopyTo(PriorityQueueItem[] array, int arrayIndex) { if (array == null) throw new ArgumentNullException("array"); if (arrayIndex < 0) throw new ArgumentOutOfRangeException("arrayIndex", "arrayIndex is less than 0."); if (array.Rank > 1) throw new ArgumentException("array is multidimensional."); if (numItems == 0) return; if (arrayIndex >= array.Length) throw new ArgumentException("arrayIndex is equal to or greater than the length of the array."); if (numItems > (array.Length - arrayIndex)) throw new ArgumentException("The number of elements in the source ICollection is greater than the available space from arrayIndex to the end of the destination array."); for (int i = 0; i < numItems; i++) { array[arrayIndex + i] = items[i]; } } #region ICollection Members public void CopyTo(Array array, int index)
  • 9. { this.CopyTo((PriorityQueueItem[])array, index); } public bool IsSynchronized { get { return false; } } public object SyncRoot { get { return items.SyncRoot; } } #endregion #region IEnumerable> Members public IEnumerator> GetEnumerator() { for (int i = 0; i < numItems; i++) { yield return items[i]; } } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } } Solution // PriorityQueue.cs // // Jim Mischel using System;
  • 10. using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; namespace Mischel.Collections { [Serializable] [ComVisible(false)] public struct PriorityQueueItem { private TValue _value; public TValue Value { get { return _value; } } private TPriority _priority; public TPriority Priority { get { return _priority; } } internal PriorityQueueItem(TValue val, TPriority pri) { this._value = val; this._priority = pri; } } [Serializable] [ComVisible(false)] public class PriorityQueue : ICollection, IEnumerable> { private PriorityQueueItem[] items; private const Int32 DefaultCapacity = 16; private Int32 capacity; private Int32 numItems; private Comparison compareFunc; ///
  • 11. /// Initializes a new instance of the PriorityQueue class that is empty, /// has the default initial capacity, and uses the default IComparer. /// public PriorityQueue() : this(DefaultCapacity, Comparer.Default) { } public PriorityQueue(Int32 initialCapacity) : this(initialCapacity, Comparer.Default) { } public PriorityQueue(IComparer comparer) : this(DefaultCapacity, comparer) { } public PriorityQueue(int initialCapacity, IComparer comparer) { Init(initialCapacity, new Comparison(comparer.Compare)); } public PriorityQueue(Comparison comparison) : this(DefaultCapacity, comparison) { } public PriorityQueue(int initialCapacity, Comparison comparison) { Init(initialCapacity, comparison); } private void Init(int initialCapacity, Comparison comparison) { numItems = 0; compareFunc = comparison; SetCapacity(initialCapacity); } public int Count { get { return numItems; }
  • 12. } public int Capacity { get { return items.Length; } set { SetCapacity(value); } } private void SetCapacity(int newCapacity) { int newCap = newCapacity; if (newCap < DefaultCapacity) newCap = DefaultCapacity; // throw exception if newCapacity < NumItems if (newCap < numItems) throw new ArgumentOutOfRangeException("newCapacity", "New capacity is less than Count"); this.capacity = newCap; if (items == null) { items = new PriorityQueueItem[newCap]; return; } // Resize the array. Array.Resize>(ref items, newCap); } public void Enqueue(PriorityQueueItem newItem) { if (numItems == capacity) { // need to increase capacity // grow by 50 percent SetCapacity((3 * Capacity) / 2); } int i = numItems; ++numItems; while ((i > 0) && (compareFunc(items[(i - 1) / 2].Priority, newItem.Priority) < 0)) {
  • 13. items[i] = items[(i - 1) / 2]; i = (i - 1) / 2; } items[i] = newItem; //if (!VerifyQueue()) //{ // Console.WriteLine("ERROR: Queue out of order!"); //} } public void Enqueue(TValue value, TPriority priority) { Enqueue(new PriorityQueueItem(value, priority)); } private PriorityQueueItem RemoveAt(Int32 index) { PriorityQueueItem o = items[index]; --numItems; // move the last item to fill the hole PriorityQueueItem tmp = items[numItems]; // If you forget to clear this, you have a potential memory leak. items[numItems] = default(PriorityQueueItem); if (numItems > 0 && index != numItems) { // If the new item is greater than its parent, bubble up. int i = index; int parent = (i - 1) / 2; while (compareFunc(tmp.Priority, items[parent].Priority) > 0) { items[i] = items[parent]; i = parent; parent = (i - 1) / 2; } // if i == index, then we didn't move the item up if (i == index) { // bubble down ...
  • 14. while (i < (numItems) / 2) { int j = (2 * i) + 1; if ((j < numItems - 1) && (compareFunc(items[j].Priority, items[j + 1].Priority) < 0)) { ++j; } if (compareFunc(items[j].Priority, tmp.Priority) <= 0) { break; } items[i] = items[j]; i = j; } } // Be sure to store the item in its place. items[i] = tmp; } //if (!VerifyQueue()) //{ // Console.WriteLine("ERROR: Queue out of order!"); //} return o; } // Function to check that the queue is coherent. public bool VerifyQueue() { int i = 0; while (i < numItems / 2) { int leftChild = (2 * i) + 1; int rightChild = leftChild + 1; if (compareFunc(items[i].Priority, items[leftChild].Priority) < 0) { return false; }
  • 15. if (rightChild < numItems && compareFunc(items[i].Priority, items[rightChild].Priority) < 0) { return false; } ++i; } return true; } public PriorityQueueItem Dequeue() { if (Count == 0) throw new InvalidOperationException("The queue is empty"); return RemoveAt(0); } /// /// Removes the item with the specified value from the queue. /// The passed equality comparison is used. /// /// The item to be removed. /// An object that implements the IEqualityComparer interface /// for the type of item in the collection. public void Remove(TValue item, IEqualityComparer comparer) { // need to find the PriorityQueueItem that has the Data value of o for (int index = 0; index < numItems; ++index) { if (comparer.Equals(item, items[index].Value)) { RemoveAt(index); return; } } throw new ApplicationException("The specified itemm is not in the queue."); } /// /// Removes the item with the specified value from the queue.
  • 16. /// The default type comparison function is used. /// /// The item to be removed. public void Remove(TValue item) { Remove(item, EqualityComparer.Default); } public PriorityQueueItem Peek() { if (Count == 0) throw new InvalidOperationException("The queue is empty"); return items[0]; } // Clear public void Clear() { for (int i = 0; i < numItems; ++i) { items[i] = default(PriorityQueueItem); } numItems = 0; TrimExcess(); } /// /// Set the capacity to the actual number of items, if the current /// number of items is less than 90 percent of the current capacity. /// public void TrimExcess() { if (numItems < (float)0.9 * capacity) { SetCapacity(numItems); } } // Contains public bool Contains(TValue o)
  • 17. { foreach (PriorityQueueItem x in items) { if (x.Value.Equals(o)) return true; } return false; } public void CopyTo(PriorityQueueItem[] array, int arrayIndex) { if (array == null) throw new ArgumentNullException("array"); if (arrayIndex < 0) throw new ArgumentOutOfRangeException("arrayIndex", "arrayIndex is less than 0."); if (array.Rank > 1) throw new ArgumentException("array is multidimensional."); if (numItems == 0) return; if (arrayIndex >= array.Length) throw new ArgumentException("arrayIndex is equal to or greater than the length of the array."); if (numItems > (array.Length - arrayIndex)) throw new ArgumentException("The number of elements in the source ICollection is greater than the available space from arrayIndex to the end of the destination array."); for (int i = 0; i < numItems; i++) { array[arrayIndex + i] = items[i]; } } #region ICollection Members public void CopyTo(Array array, int index) { this.CopyTo((PriorityQueueItem[])array, index); } public bool IsSynchronized {
  • 18. get { return false; } } public object SyncRoot { get { return items.SyncRoot; } } #endregion #region IEnumerable> Members public IEnumerator> GetEnumerator() { for (int i = 0; i < numItems; i++) { yield return items[i]; } } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } }