Last active
June 2, 2020 12:47
-
-
Save Ch-sriram/c2ccd12e714379c17b27c360baaeab67 to your computer and use it in GitHub Desktop.
Selection Sort Recursive Algorithm O(N^2)
This file contains hidden or 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
| #include <iostream> | |
| #include <vector> | |
| #include <algorithm> // for swap() | |
| #include <climits> // for INT_MIN | |
| using namespace std; | |
| void select_sort_rec(vector<int> &ar, vector<int> &swaps_eles, int n, int max_ele = INT_MIN, int max_idx = -1) { | |
| // Base Case | |
| if(n == 1) return; | |
| for(int j = 0; j < n; ++j) | |
| if(max_ele < ar[j]) { | |
| max_ele = ar[j]; | |
| max_idx = j; | |
| } | |
| swap(ar[max_idx], ar[n-1]); | |
| swaps_eles.push_back(max_idx); | |
| select_sort_rec(ar, swaps_eles, n-1); | |
| } | |
| int main() { | |
| int t; cin >> t; | |
| while(t--) { | |
| int n; cin >> n; | |
| vector<int> ar(n); | |
| for(int i = 0; i < n; ++i) | |
| cin >> ar[i]; | |
| vector<int> swaps_eles; | |
| select_sort_rec(ar, swaps_eles, ar.size()); | |
| // for(auto x: ar) cout << x << " "; // sorted array | |
| for(auto x: swaps_eles) cout << x << " "; // the indices where the swaps occured | |
| cout << "\n"; | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment