Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
HeapSort
//g++ 7.4.0 //Heap Sort //heapify, heapSort and printArray codes credit to Geeks For Geeks //template modifications,swap and test driver codes are created by Rezaul Hoque on April 1,2021 //please contact at jewelmrh@yahoo.com #include <iostream> using namespace std; template <class T> void heapify(T arr[], int n, int i) { int largest = i; int l = 2 * i + 1; int r = 2 * i + 2; if (l < n && arr[l] > arr[largest]) largest = l; if (r < n && arr[r] > arr[largest]) largest = r; if (largest != i) { swap(arr[i], arr[largest]); heapify(arr, n, largest); } } template <class T> void heapSort(T arr[], int n) { for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); for (int i = n - 1; i >= 0; i--) { swap(arr[0], arr[i]); heapify(arr, i, 0); } } template <class T> void swap(T& x, T& y) { T temp; temp = x; x=y; y=temp; } template <class T> void printArray(T arr[], int n) { for (int i = 0; i < n; ++i) cout << arr[i] << " "; cout << "\n"; } int main() { int arr[] = { 7,6,5,4,3,2}; char carr[]={'f','d','c','b','a'}; int n = sizeof(arr) / sizeof(arr[0]); int n2=sizeof(carr)/sizeof(carr[0]); cout<<"Before heap sort \n"; printArray(arr, n); printArray(carr,n2); heapSort(arr, n); heapSort(carr,n2); cout << "After heap sort \n"; printArray(arr, n); printArray(carr,n2); return 0; }
run
|
edit
|
history
|
help
0
11933
combine c++ string with dynamically allocated c array of chars through overloaded add operator
Suma
HashFold
random
VolAreObject
ThreadPool
merge without extra space Gap method ALgorithm
Simulare 2022
TupleCPP