0% found this document useful (0 votes)
13 views3 pages

HEAP

The document contains a C++ implementation of the Heap Sort algorithm. It includes functions for displaying the heap, heapifying, building the heap, and sorting the array. The main function demonstrates sorting an array of integers and outputs the sorted result.

Uploaded by

omkarshivajirao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views3 pages

HEAP

The document contains a C++ implementation of the Heap Sort algorithm. It includes functions for displaying the heap, heapifying, building the heap, and sorting the array. The main function demonstrates sorting an array of integers and outputs the sorted result.

Uploaded by

omkarshivajirao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

#include <iostream>

void display(int heap[], int n) {


for (int i = 0; i < n; i++) {
std::cout << heap[i] << " ";
}
std::cout << std::endl;
}

void Heapify(int heap[], int i, int n) {


int curr = i;
int l = (2 * curr) + 1;
int r = (2 * curr) + 2;

while (l < n) {
int largest = curr;
if (heap[l] > heap[largest]) {
largest = l;
}
if (r < n && heap[r] > heap[largest]) {
largest = r;
}
if (curr != largest) {
int temp = heap[curr];
heap[curr] = heap[largest];
heap[largest] = temp;

curr = largest;
l = (2 * curr) + 1;
r = (2 * curr) + 2;
} else {
break;
}
}
}

void BuildHeap(int heap[], int n) {


int start = (n / 2) - 1;
for (int i = start; i >= 0; i--) {
Heapify(heap, i, n);
}
}

void HeapSort(int heap[], int n) {


BuildHeap(heap, n);
int size = n;
while (size > 1) {

int temp = heap[0];


heap[0] = heap[size - 1];
heap[size - 1] = temp;

size--;
Heapify(heap, 0, size);
}
}
int main() {
int heap[] = {7, 20, 12, 40, 21, 13};
int n = sizeof(heap) / sizeof(heap[0]);

HeapSort(heap, n);

std::cout << "Sorted array: ";


display(heap, n);

return 0;
}

OUTPUT:
> cd "c:\Users\Ruhan Tejwani\OneDrive\Desktop\c++
course\.vscode\FDS\" ; if ($?) { g++ HEAP.cpp -o HEAP } ; if ($?) { .\HEAP }
Sorted array: 7 12 13 20 21 40

You might also like