CJamie

selectionSort

Mar 24th, 2022
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.85 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. void _swap(int &a, int &b) {
  4. swap(a, b);
  5. cout<<"swapped "<<a<<" & "<<b<<"\n";
  6. }
  7. void print(vector<int> a, int i) {
  8. cout << "iteration #" << i << " : ";
  9. for(auto x: a)
  10. cout << x << " ";
  11. cout<<endl;
  12. }
  13. void sel_sort(vector<int> a, int n) {
  14. int min;
  15. for (int i = 0; i < n - 1; i++) {
  16. min = i;
  17. for (int j = i + 1; j < n; j++) {
  18. if (a[j] < a[min])
  19. min = j;
  20. }
  21. if (min != i)
  22. _swap(a[min], a[i]);
  23. print(a, i+1);
  24. }
  25. cout << "\nselection sorted array: ";
  26. for (auto x: a) cout << x << " ";
  27. }
  28. int main()
  29. {
  30. int n;
  31. // cout << "enter size & elements of the array \n";
  32. cin >> n;
  33. vector<int> a(n);
  34. for (auto &x: a) cin >> x;
  35. sel_sort(a, n);
  36. return 0;
  37. }
Advertisement
Add Comment
Please, Sign In to add comment