您的位置:首页 > 其它

堆的建立, 元素插入, 删除的实现...

2010-07-29 11:22 309 查看
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <ctime>
#include <vector>
using namespace std;
const int MAX = 200;
void filerDown(int heap[], int start, int end)
{
int i = start;
int j = 2 * i + 1;
int temp = heap[i];

while(j < end)
{
if(j < end - 1 && heap[j] > heap[j + 1])
j++;

if(temp < heap[j])
break;
else
{
heap[i] = heap[j];
i = j;
j = 2 * j + 1;
}
}
heap[i] = temp;
}
void filerUp(int heap[], int start)
{
int i = start;
int j = (i - 1) / 2;
int temp = heap[i];

while(i > 0)
{
if(temp >= heap[j])
break;
else
{
heap[i] = heap[j];
i = j;
j = (j - 1) / 2;
}
}
heap[i] = temp;
}
void insert(int heap[], int value, int& count)
{
heap[count] = value;
filerUp(heap, count);
count++;
}
void dele(int heap[], int& count)
{
heap[0] = heap[count - 1];
count--;
filerDown(heap, 0, count - 1);
}
void createHeap(int heap[], int count)
{
int curSize = count;
int curPos = (curSize - 2) / 2;

while(curPos >= 0)
{
filerDown(heap, curPos, curSize);
curPos--;
}
}
int main(int argc, char *argv[])
{
int heap[MAX];
int count = 100;
vector<int> vec;

srand((unsigned)time(NULL));

for(int i=0; i<count; i++)
{
int value = rand() % 1000;
heap[i] = value;
vec.push_back(value);
}

cout << " all elements are: " << endl;
sort(vec.begin(), vec.end());
for(int i=0; i<count; i++)
cout << vec.at(i) << " ";
cout << endl;

cout << "min element is: " << endl;
createHeap(heap, count);
cout << heap[0] << endl;

cout << "after insert value 5" << endl;
insert(heap, 5, count);
cout << heap[0] << endl;

cout << "after delete the min value" << endl;
dele(heap, count);
cout << heap[0] << endl;

system("PAUSE");
return EXIT_SUCCESS;
}
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐