0% found this document useful (0 votes)
12 views

Lecture-074 1 Heap Introduction - CPP

Uploaded by

maragonirohansai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Lecture-074 1 Heap Introduction - CPP

Uploaded by

maragonirohansai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

1 #include<bits/stdc++.

h>usingnamespaceclassHeappublicint100intHeap0-10voidinsert
(intintwhile1int2ifswapelsereturn// void deleteHeap() {// if(size == 0) {// cout <<
"Heap is empty!" << endl;// return;// }// arr[1] = arr[size];// size--;// int i = 1;
// while(i < size) {// int leftChild = 2*i;// int rightChild = (2*i) + 1;//
if(leftChild < size && arr[i] < arr[leftChild]) {// swap(arr[i], arr[leftChild]);// i
= leftChild;// } else if(rightChild < size && arr[i] < arr[rightChild]) {//
swap(arr[i], arr[rightChild]);// i = rightChild;// } else {// return;// }
// }// }voiddeleteHeap()if0"Heap is empty!"return1int1whileint2int21intifififreturnelse
swapvoidprint()"Max Heap : "forint1" "voidheapify(intintintintint2int21ifififswapheapifyint
main()insert50insert40insert60insert30insert55insert70insert20printdeleteHeapprintint6
-15453555250int5forint20heapify"Heapified array : "forint1" "return0</span>
2 std;
3 {
4 :
5 arr[];
6 size;
7 () {
8 arr[] = ;
9 size = ;
10 }
11 val)</span></span>{
12 index = ++size;
13 arr[index] = val;
14 (index > ) {
15 parent = index/;
16 (arr[parent] < arr[index]) {
17 (arr[parent], arr[index]);
18 index = parent;
19 } {
20 ;
21 }
22 }
23 }</span>{
24 (size == ) {
25 cout << << endl;
26 ;
27 }
28 arr[] = arr[size];
29 size--;
30 i=;
31 (i < size) {
32 leftChild = *i;
33 rightChild = (*i) + ;
34 largest = i;
35 (leftChild <= size && arr[largest] < arr[leftChild]) {
36 largest = leftChild;
37 }
38 (rightChild <= size && arr[largest] < arr[rightChild]) {
39 largest = rightChild;
40 }
41 (largest == i) {
42 ;
43 } {
44 (arr[i], arr[largest]);
45 i = largest;
46 }
47 }
48 }</span>{
49 cout << ;
50 ( i=; i<=size; i++) {
51 cout << arr[i] << ;
52 }
53 cout << endl;
54 }
55 };
56 arr[], n, i)</span></span>{
57 largest = i;
58 left = *i;
59 right = *i + ;
60 (left <= n && arr[largest] < arr[left]) {
61 largest = left;
62 }
63 (right <= n && arr[largest] < arr[right]) {
64 largest = right;
65 }
66 (largest != i) {
67 (arr[i], arr[largest]);
68 (arr, n, largest);
69 }
70 }</span>{
71 Heap h;
72 h.();
73 h.();
74 h.();
75 h.();
76 h.();
77 h.();
78 h.();
79 h.();
80 h.();
81 h.();
82 arr[] = {, , , , , };
83 n=;
84 ( i = n/; i>; i--) {
85 (arr, n, i);
86 }
87 cout << ;
88 ( i=; i<=n; i++) {
89 cout << arr[i] << ;
90 }
91 cout << endl;
92 ;
93 }

You might also like