fork download
  1. //
  2. // main.cpp
  3. // Selection Sort
  4. //
  5. // Created by Himanshu on 29/08/21.
  6. //
  7.  
  8. #include <iostream>
  9. using namespace std;
  10.  
  11. void printArray (int arr[], int n) {
  12. for (int i=0; i<n; i++) {
  13. cout<<arr[i]<<" ";
  14. }
  15. cout<<endl;
  16. }
  17.  
  18. void selectionSort(int arr[], int n) {
  19. cout<<"Initial array:"<<endl;
  20. printArray(arr, n);
  21.  
  22. cout<<"Selection sort"<<endl;
  23.  
  24. for (int i=0; i<n-1; i++) {
  25. int indexMin = i;
  26. for (int j=i+1; j<n; j++) {
  27. if (arr[j] < arr[indexMin]) {
  28. indexMin = j;
  29. }
  30. }
  31. if (indexMin != i) {
  32. swap(arr[i], arr[indexMin]);
  33. }
  34. cout<<"Array after "<<(i+1)<<" iteration: "<<endl;
  35. printArray(arr, n);
  36. }
  37. }
  38.  
  39. int main() {
  40. int arr[] = {21, 15, 30, 13 , 2};
  41. int n = 5;
  42. selectionSort(arr, n);
  43. return 0;
  44. }
  45.  
Success #stdin #stdout 0s 5440KB
stdin
Standard input is empty
stdout
Initial array:
21 15 30 13 2 
Selection sort
Array after 1 iteration: 
2 15 30 13 21 
Array after 2 iteration: 
2 13 30 15 21 
Array after 3 iteration: 
2 13 15 30 21 
Array after 4 iteration: 
2 13 15 21 30