الأحد، 16 مارس 2014
7:45 ص

heap (complete binary tree)

// Heap.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include<iostream>
#include<conio.h>
#define max 7
using namespace std;
class heap
{
private:
int  a[max];
int count;
public:
heap()
{
count = 0;
}
bool insert(int key)
{
if (count == max)
return false;
a[count] = key;
moveup(count++);
return true;
}
void moveup(int index)
{
int parent = (index - 1) / 2;
int bottom = a[index];
while (index > 0 && a[parent] <bottom)
{
a[index] = a[parent];
index = parent;
parent = (parent - 1) / 2;
}
a[index] = bottom;
}
void movedown(int index)
{
int largechild;
int top = a[index];
while (index<count / 2)
{
int leftchild = 2 * index + 1;
int rightchild = 2 * index + 2;
if (rightchild<count && a[leftchild] < a[rightchild])
largechild = rightchild;
else
largechild = leftchild;
if (top >= a[largechild])
break;
a[index] = a[largechild];
index = largechild;
}
a[index] = top;
}

int remove()

{
if (count == 0)
{
cout << "heap is empty" << endl;
return -1;
}
int root = a[0];
a[0] = a[--count];
movedown(0);
return root;
}
void display()
{
for (int i = 0; i <count; i++)
cout << a[i]<<" ";
cout << endl;
}

};


void main()

{
heap h;
h.insert(50);
h.insert(20);
h.insert(30);
h.insert(10);
h.insert(40);
h.insert(70);
h.insert(60);
h.display();
h.remove();
h.display();
_getch();
}








For more advantage in show:-















void display()
{
cout <<"\t\t\t\t    ("<< a[0] <<")" <<endl;
cout << "\t\t\t\t   /" << "    |" << endl;
cout << "\t\t\t\t  /" << "     |" << endl;
cout << "\t\t\t      (" << a[1] << ")\t(" << a[2] << ")" << endl;
cout << "\t\t\t      /" << "  |" <<"     / " << "  | " << endl;
cout << "\t\t\t     /" << "   |" <<"    / " << "   | " << endl;
cout << "\t\t\t  (" << a[3] << ") (" << a[4] << ")  (" << a[5] << ") ("<<a[6]<<")";
cout << endl;
}

0 التعليقات:

إرسال تعليق