SlideShare a Scribd company logo
// 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.pdf
NicholasflqStewartl
 
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
sktambifortune
 
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
annaimobiles
 
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
NicholasflqStewartl
 
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.pdf
fcsondhiindia
 
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
gerardkortney
 
Infinum Android Talks #20 - DiffUtil
Infinum Android Talks #20 - DiffUtilInfinum Android Talks #20 - DiffUtil
Infinum Android Talks #20 - DiffUtil
Infinum
 
(674335607) cs2309 java-lab-manual
(674335607) cs2309 java-lab-manual(674335607) cs2309 java-lab-manual
(674335607) cs2309 java-lab-manual
Chandrapriya Jayabal
 
F# in the enterprise
F# in the enterpriseF# in the enterprise
F# in the enterprise
7sharp9
 
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
deepaksatrker
 
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
flashfashioncasualwe
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
Lars Jankowfsky
 
OBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .pptOBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .ppt
SaadAsim11
 
Build Widgets
Build WidgetsBuild Widgets
Build Widgets
scottw
 
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
fashiongallery1
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
Tomek 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.pdf
charanjit1717
 

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](.pdf
rajat630669
 
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
rajat630669
 
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
rajat630669
 
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
rajat630669
 
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
rajat630669
 
}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
rajat630669
 
y=41.2xSolutiony=41.2x.pdf
y=41.2xSolutiony=41.2x.pdfy=41.2xSolutiony=41.2x.pdf
y=41.2xSolutiony=41.2x.pdf
rajat630669
 
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
rajat630669
 
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
rajat630669
 
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
rajat630669
 
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
rajat630669
 
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
rajat630669
 
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
rajat630669
 
P = 12SolutionP = 12.pdf
P = 12SolutionP = 12.pdfP = 12SolutionP = 12.pdf
P = 12SolutionP = 12.pdf
rajat630669
 
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
rajat630669
 
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
rajat630669
 
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
rajat630669
 
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
rajat630669
 
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
rajat630669
 
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
rajat630669
 

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

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 

Recently uploaded (20)

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 

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 } }