fork download
  1. //Maxwell Brewer CS1A Chapter 8, p. 488, #9
  2. //
  3. /*******************************************************************************
  4.  * SORTING BENCHMARKS
  5.  * _____________________________________________________________________________
  6.  * This program will compare the efficiency of Bubble Sort and Selection Sort
  7.  * by counting the number of exchanges each algorithm makes when sorting the
  8.  * same list of numbers.
  9.  * _____________________________________________________________________________
  10.  * INPUT
  11.  * None (The array of numbers is predefined).
  12.  *
  13.  * OUTPUT
  14.  * The number of exchanges made by each sorting algorithm.
  15.  *
  16.  ******************************************************************************/
  17.  
  18. #include <iostream>
  19. using namespace std;
  20.  
  21. // Bubble Sort function definition
  22. int bubbleSort(int arr[], int size)
  23. {
  24. int count = 0; // Counter for number of exchanges
  25.  
  26. // Bubble Sort algorithm
  27. for (int i = 0; i < size - 1; i++)
  28. {
  29. for (int j = 0; j < size - i - 1; j++)
  30. {
  31. if (arr[j] > arr[j + 1])
  32. {
  33. // Swap adjacent elements if they are in the wrong order
  34. int temp = arr[j];
  35. arr[j] = arr[j + 1];
  36. arr[j + 1] = temp;
  37. count++; // Increment exchange count
  38. }
  39. }
  40. }
  41.  
  42. return count;
  43. }
  44.  
  45. int selectionSort(int arr[], int size)
  46. {
  47. int pos, count = 0; // Variables to store minimum position
  48. // and exchange count
  49.  
  50. // Selection Sort algorithm
  51. for (int i = 0; i < size - 1; i++)
  52. {
  53. pos = i; // Assume the current element is the minimum
  54.  
  55. for (int j = i + 1; j < size; j++)
  56. {
  57. if (arr[pos] > arr[j])
  58. pos = j; // Update position of minimum element
  59. }
  60.  
  61. // Swap elements if a new minimum is found
  62. if (pos != i)
  63. {
  64. int temp = arr[i];
  65. arr[i] = arr[pos];
  66. arr[pos] = temp;
  67. count++; // Increment exchange count
  68. }
  69. }
  70.  
  71. return count;
  72. }
  73.  
  74. int main()
  75. {
  76. // Initialize arrays with identical values for fair comparison
  77. int arr [] = {1, 4, 6, 2, 3, 7, 8, 5, 12, 18, 14,
  78. 19, 9, 15, 10, 11, 20, 13, 17, 16};
  79.  
  80. int arr1[] = {1, 4, 6, 2, 3, 7, 8, 5, 12, 18, 14,
  81. 19, 9, 15, 10, 11, 20, 13, 17, 16};
  82. int n = 20;
  83.  
  84. // Call sorting functions and display the number of exchanges for each
  85. cout << "\nThe number of exchanges made in Bubble Sort is: "
  86. << bubbleSort(arr, n);
  87.  
  88. cout << "\n\nThe number of exchanges made in Selection Sort is: "
  89. << selectionSort(arr1, n);
  90.  
  91. return 0;
  92. }
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
The number of exchanges made in Bubble Sort is: 36

The number of exchanges made in Selection Sort is: 16