Using System;
Using System.Collections;
Namespace Datastructure
{
<summary>
Summary description of the binaryheap. -------binary heap (based on array implementation)
</summary>
public class Binaryheap:ipriorityqueue
{
protected ArrayList Array;
Create an empty binary heap that accommodates up to _length objects
Public binaryheap (UINT _length)
{
//
TODO: Add constructor logic here
//
Array=new ArrayList ((int) _length);
Array. capacity= (int) _length;
}
Number of objects in the heap
public virtual int count{get{return This.array.Count;}}
Converts an array of members into a 1-base representation
Public virtual Object Item (int _i)
{
if (_i>=this.array.capacity)
throw new Exception ("My:out of Index");/not out of bounds
return this.array[_i-1];
}
#region Ipriorityqueue Members
First place the hole in the next position in the array, which is I (Note: cardinality is 1 and then compared to the number on the [I/2] position, if less than the hole is moved to the [I/2] position, and the original [I/2] position is moved to [i], otherwise the void becomes _obj----so recursive
public void Enqueue (Object _obj)
{
TODO: Add Binaryheap.enqueue implementation
if (this.array.count==this.array.capacity)
throw new Exception ("My:priority queue is full");//If the priority queue is filled, throw an exception
THIS.ARRAY.ADD (New object ());
int i=this.array.count;
while (I>1&&comparer.default.compare (this.array[i/2-1],_obj) >0)
{
This. Item (i) =this. Item (I/2);
THIS.ARRAY[I-1]=THIS.ARRAY[I/2-1];
i/=2;
}
This.array[i-1]=_obj;
}
public Object Findmin ()
{
TODO: Add binaryheap.findmin implementation
if (this.array.count==0)
throw new Exception ("My:priority queue is empty");//If the queue is empty, throw an exception
return this.array[0];
}
public Object Dequeuemin ()
{
TODO: Add binaryheap.dequeuemin implementation
Object Tmpobj=this. Findmin ();
int i=1;
while ((2*i+1) <=this.array.count)
{
if (Comparer.Default.Compare (This.array[2*i-1],this.array[2*i]) <=0)
{
THIS.ARRAY[I-1]=THIS.ARRAY[2*I-1];
This.array[2*i-1]=tmpobj;
I=2*i;
}
Else
{
This.array[i-1]=this.array[2*i];
This.array[2*i]=tmpobj;
i=2*i+1;
}
}
Object delobj=this.array[i-1];//temporarily stores the elements to be deleted
if (i!=this.array.count)//If the object being searched is the last object of the array, do nothing
{
this.array[i-1]=this.array[this.array.count-1];//fill the Void
}
This.array.RemoveAt (this.array.count-1);//delete the last object
return delobj;
}
#endregion
}
}