0% found this document useful (0 votes)
3 views2 pages

Heapsort CPP

The document contains a C++ implementation of the Heapsort algorithm, including functions for heapifying an array and building a max heap. It prompts the user to enter the number of elements and the elements themselves, then displays the resulting max heap. The code utilizes standard input/output functions and basic array manipulation techniques.

Uploaded by

Aniruddh Dixit
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)
3 views2 pages

Heapsort CPP

The document contains a C++ implementation of the Heapsort algorithm, including functions for heapifying an array and building a max heap. It prompts the user to enter the number of elements and the elements themselves, then displays the resulting max heap. The code utilizes standard input/output functions and basic array manipulation techniques.

Uploaded by

Aniruddh Dixit
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

5/8/26, 11:13 AM HEAPSORT.

CPP

ADA\[Link]

1 #include <iostream.h>
2 #include <conio.h>
3
4 void heapify(int a[], int n, int i)
5 {
6 int largest, left, right, temp;
7
8 largest = i;
9 left = 2 * i;
10 right = 2 * i + 1;
11
12 if (i <= n && a[left] > a[largest])
13 largest = left;
14
15 if (i <= n && a[right] > a[largest])
16 largest = right;
17
18 if (largest != i)
19 {
20 temp = a[i];
21 a[i] = a[largest];
22 a[largest] = temp;
23
24 heapify(a, n, largest);
25 }
26 }
27
28 void buildMaxHeap(int a[], int n)
29 {
30 int i;
31
32 for (i = n / 2; i >= 1; i--)
33 heapify(a, n, i);
34 }
35
36 void main()
37 {
38 int a[100], n, i;
39
40 clrscr();
41
42 cout << "Enter number of elements: ";
43 cin >> n;
44
45 cout << "Enter elements:\n";
46 for (i = 1; i <= n; i++)
47 cin >> a[i];
48

localhost:63766/d8494180-b33f-49f0-8816-84564b95f18b/ 1/2
5/8/26, 11:13 AM [Link]

49 buildMaxHeap(a, n);
50
51 cout << "\nMax Heap is:\n";
52 for (i = 1; i <= n; i++)
53 cout << a[i] << " ";
54
55 getch();
56 }

localhost:63766/d8494180-b33f-49f0-8816-84564b95f18b/ 2/2

You might also like