Skip to content

Commit eb1406b

Browse files
authored
Merge pull request nitishji#3 from nitin21897/nitin21897-radix.cpp
Add files via upload
2 parents 5bc0746 + 52c3dfb commit eb1406b

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

radix.cpp

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
2+
// C++ program for implementation of Heap Sort
3+
#include <iostream>
4+
5+
using namespace std;
6+
7+
// To heapify a subtree rooted with node i which is
8+
// an index in arr[]. n is size of heap
9+
void heapify(int arr[], int n, int i)
10+
{
11+
int largest = i; // Initialize largest as root
12+
int l = 2*i + 1; // left = 2*i + 1
13+
int r = 2*i + 2; // right = 2*i + 2
14+
15+
// If left child is larger than root
16+
if (l < n && arr[l] > arr[largest])
17+
largest = l;
18+
19+
// If right child is larger than largest so far
20+
if (r < n && arr[r] > arr[largest])
21+
largest = r;
22+
23+
// If largest is not root
24+
if (largest != i)
25+
{
26+
swap(arr[i], arr[largest]);
27+
28+
// Recursively heapify the affected sub-tree
29+
heapify(arr, n, largest);
30+
}
31+
}
32+
33+
// main function to do heap sort
34+
void heapSort(int arr[], int n)
35+
{
36+
// Build heap (rearrange array)
37+
for (int i = n / 2 - 1; i >= 0; i--)
38+
heapify(arr, n, i);
39+
40+
// One by one extract an element from heap
41+
for (int i=n-1; i>=0; i--)
42+
{
43+
// Move current root to end
44+
swap(arr[0], arr[i]);
45+
46+
// call max heapify on the reduced heap
47+
heapify(arr, i, 0);
48+
}
49+
}
50+
51+
/* A utility function to print array of size n */
52+
void printArray(int arr[], int n)
53+
{
54+
for (int i=0; i<n; ++i)
55+
cout << arr[i] << " ";
56+
cout << "\n";
57+
}
58+
59+
// Driver program
60+
int main()
61+
{
62+
int arr[] = {12, 11, 13, 5, 6, 7};
63+
int n = sizeof(arr)/sizeof(arr[0]);
64+
65+
heapSort(arr, n);
66+
67+
cout << "Sorted array is \n";
68+
printArray(arr, n);
69+
}
70+

0 commit comments

Comments
 (0)