Skip to content
This repository
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

file 156 lines (139 sloc) 2.005 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
#ifndef _QUEUE_H_
#define _QUEUE_H_

#include<iostream>

using namespace std;

const int MAX_SIZE = 1000;
const int MIN = -1;

class PriorityQueue
{
public:
PriorityQueue();
void Insert(int key);
int Maximum();
int ExtractMax();
void IncreaseKey(int i, int key);
void DecreaseKey(int i, int key);
int Length();

private:
int array[MAX_SIZE];
int length;

void MaxHeapify(int i);
};

PriorityQueue::PriorityQueue()
{
length = 0;
}

void PriorityQueue::MaxHeapify(int i)
{
int left, right;
int largest;
int temp;

while(1)
{
left = 2*i+1;
right = 2*i+2;
if(left < length && array[left] > array[i])
{
largest = left;
}
else
{
largest = i;
}
if(right < length && array[right] > array[largest])
{
largest = right;
}
if(i != largest)
{
temp = array[i];
array[i] = array[largest];
array[largest] = temp;
i = largest;
}
else
{
break;
}
}
}

int PriorityQueue::ExtractMax()
{
if(length < 1)
{
cout << "underflow" << endl;
return -1;
}
else
{
int max;
max = array[0];
array[0] = array[length-1];
length--;
MaxHeapify(0);
return max;
}
}

int PriorityQueue::Maximum()
{
if(length == 0)
{
cout << "empty" << endl;
return -1;
}
else
{
return array[0];
}
}

void PriorityQueue::IncreaseKey(int i, int key)
{
if(key < array[i])
{
cout << "new key is smaller than current key" << endl;
}
else
{
int parents;
int temp;

array[i] = key;
while(1)
{
parents = (i-1)/2;
if(i > 0 && array[parents] < array[i])
{
temp = array[i];
array[i] = array[parents];
array[parents] = temp;
i = parents;
}
else
{
break;
}
}
}
}

void PriorityQueue::Insert(int key)
{
array[length] = MIN;
length++;
IncreaseKey(length-1,key);
}

void PriorityQueue::DecreaseKey(int i, int key)
{
if(key > array[i])
{
cout << "new key is larger than current key" << endl;
}
else
{
array[i] = key;
MaxHeapify(i);
}
}

int PriorityQueue::Length()
{
return length;
}

#endif
Something went wrong with that request. Please try again.