fork download
  1. #include<iostream>
  2.  
  3. using namespace std;
  4.  
  5. // Function to perform Selection Sort
  6. void selection_sort(int n, int arr[])
  7. {
  8. // Display the sorting method being used
  9. cout << "selection sort" << endl;
  10.  
  11. // Variables to count comparisons and swaps
  12. int cnt_comp = 0, cnt_sw = 0;
  13.  
  14. // Move the boundary of the unsorted portion one step at a time
  15. for(int j = 0; j < n - 1; j++)
  16. {
  17. // Assume the current position contains the smallest element
  18. int smallest = j;
  19.  
  20. // Search for the smallest element in the remaining unsorted array
  21. for(int i = j + 1; i < n; i++)
  22. {
  23. // Compare current element with the current smallest element
  24. if(arr[i] < arr[smallest])
  25. smallest = i; // Update index of the smallest element found
  26. }
  27.  
  28. // Swap the smallest element with the first unsorted element
  29. int tmp = arr[j];
  30. arr[j] = arr[smallest];
  31. arr[smallest] = tmp;
  32.  
  33. // Increment swap counter
  34. cnt_sw++;
  35. }
  36.  
  37. // Display the number of comparisons performed
  38. // (Note: cnt_comp is declared but not incremented in this code)
  39. cout << "Number of comparisons: " << cnt_comp << endl;
  40.  
  41. // Display the number of swaps performed
  42. cout << "Number of exchange: " << cnt_sw << endl;
  43. }
  44.  
  45. int main()
  46. {
  47. // Size of the array
  48. int n = 100;
  49.  
  50. // Declare an array of 100 elements
  51. int arr[100];
  52.  
  53. // Initialize array in descending order (worst-case style input)
  54. for(int i = 0; i < 100; i++)
  55. arr[i] = 100 - i;
  56.  
  57. // Sort the descending array
  58. selection_sort(n, arr);
  59.  
  60. // Reinitialize array in ascending order (already sorted input)
  61. for(int i = 0; i < 100; i++)
  62. arr[i] = i;
  63.  
  64. // Sort the already sorted array
  65. selection_sort(n, arr);
  66.  
  67. // Print the final array contents
  68. for(int i = 0; i < 100; i++)
  69. {
  70. cout << arr[i] << " ";
  71. }
  72.  
  73. return 0;
  74. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
selection sort
Number of comparisons: 0
Number of exchange: 99
selection sort
Number of comparisons: 0
Number of exchange: 99
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99