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
|
#include <iostream>
#include <fstream>
#include <math.h>
using namespace std;
void readFile();
void insertHeap(int, int);
void siftUp(int);
void swap(int, int, int arr[]);
void display(int);
void siftDown(int, int);
int deleteHeap(int);
ifstream in("input.txt");
int arr[10];
int main()
{
int heapSize = 4;
readFile();
display(heapSize);
heapSize = deleteHeap(heapSize);
display(heapSize)
return 0;
}
void readFile()
{
int data, i = 0;
while (in.good())
{
if (in >> data)
{
insertHeap(data, i);
++i;
}
else
{
cout << "File empty...";
exit(100);
}
}
}
void insertHeap(int data, int i)
{
arr[i] = data;
siftUp(i);
}
void siftUp(int i)
{
if (i != 0)
{
int parent = (i - 1)/2;
if (arr[parent] > arr[i])
{
swap(parent, i, arr);
siftUp(parent);
}
}
}
void swap(int a, int b, int arr[])
{
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
//not my work
void display(int heapSize)
{
int value = 1;
int power = 0;
for (int i = 0; i <= heapSize; ++i)
{
if (i == value)
{
cout << endl;
power += 1;
//1 << power ?
value += (1 << power);
}
cout << arr[i] << " ";
}
cout << endl << endl;
}
//always deletes first element in array, swaps w/ last element then work your way down
void siftDown(int parent, int heapSize)
{
int min;
int lChild = 2*parent+1;
int rChild = 2*parent+2;
//if theres another value other than root
if (lChild <= heapSize)
{
//if there's only a left child
if (lChild == heapSize)
min = lChild;
//if there's also a right child
else
{
//compare left and right child
if (arr[lChild] < arr[rChild])
min = lChild;
else
min = rChild;
//if the parent > min child, swap
if (arr[parent] > arr[min])
{
swap(parent, min, arr);
//continue until lChild becomes greater than heapSize
siftDown(min, heapSize);
}
}
}
}
int deleteHeap(int heapSize)
{
arr[0] = arr[heapSize];
arr[heapSize] = '\0';
heapSize--;
siftDown(0, heapSize);
return heapSize;
}
|