Created
April 25, 2020 14:12
-
-
Save m-primo/5bbc8dd02c9708bc9dc33bcd449198cd to your computer and use it in GitHub Desktop.
Simple Heap Implementation in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void swap(int &a, int &b) { | |
int temp = a; | |
a = b; | |
b = temp; | |
} | |
void showArray(int arr[], int size) { | |
for(int i = 0; i < size; i++) { | |
cout << arr[i] << ", "; | |
} | |
cout << endl; | |
} | |
void bubbleSort(int arr[], int size) { | |
for(int i = 0; i < size - 1; i++) { | |
for(int j = 0; j < size - 1; j++) { | |
if(arr[j] > arr[j + 1]) { | |
swap(arr[j], arr[j + 1]); | |
} | |
} | |
} | |
} | |
void selectionSort(int arr[], int size) { | |
for(int i = 0; i < size - 1; i++) { | |
for(int j = i + 1; j < size; j++) { | |
if(arr[i] > arr[j]) { | |
swap(arr[i], arr[j]); | |
} | |
} | |
} | |
} | |
void insertionSort(int arr[], int size) { | |
for(int i = 1; i < size; i++) { | |
for(int j = i; j >= 1; j--) { | |
if(arr[j] < arr[j - 1]) { | |
swap(arr[j], arr[j - 1]); | |
} else break; | |
} | |
} | |
} | |
void countSort(int arr[],int size) { | |
int k = 0; | |
int *arr = new int[size]; | |
for(int i = 1; i <= size; i++) { | |
if(arr[i] > k) k = arr[i]; | |
} | |
int arr_index[k], output[size]; | |
for(int i = 0; i < k+1; i++) arr_index[i] = 0; | |
for(int j = 1; j <= size; j++) arr_index[arr[j]]++; | |
for(int i = 1; i <= k; i++) arr_index[i] += arr_index[i-1]; | |
for(int j = size; j >= 1; j--) { | |
output[arr_index[arr[j]]] = arr[j]; | |
arr_index[arr[j]]--; | |
} | |
} | |
int main() { | |
int arr[] = {45,23,35,422,51,74,755,154,1,22,10}; | |
int size = sizeof(arr) / sizeof(int); | |
showArray(arr, size); | |
//sort function here | |
showArray(arr, size); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment