fork download
  1. //Natalie Zarate CSC5 Chapter 8, P. 488, #9
  2. #include <iostream>
  3. #include <iomanip>
  4. using namespace std;
  5.  
  6. //Prototype for BubbleSort
  7. int BubbleSort(int numbers[], int elements);
  8.  
  9. // Prototype for SelectionSort
  10. int SelectionSort(int numbers[], int elements);
  11.  
  12. int main()
  13. {
  14. int size = 20;
  15. int array1[size] = {7, 14, 11, 20, 15, 12, 13, 6, 5, 4, 17, 8, 1, 19, 2, 9,
  16. 3, 10, 14, 16, 18};
  17. int array2[size] = {7, 14, 11, 20, 15, 12, 13, 6, 5, 4, 17, 8, 1, 19, 2, 9,
  18. 3, 10, 14, 16, 18};
  19. int BubbleCount;
  20. int SelectCount;
  21.  
  22. //Call BubbleSort
  23. BubbleCount = BubbleSort(array1, size);
  24.  
  25. //Call SelectionSort
  26. SelectCount = SelectionSort(array2, size);
  27.  
  28. cout << BubbleCount << endl;
  29.  
  30. for (int i = 0; i < size; i++)
  31. {
  32. cout << array1[i] << " ";
  33. }
  34.  
  35. cout << "\n" << SelectCount << endl;
  36.  
  37. for (int i = 0; i < size; i++)
  38. {
  39. cout << array2[i] << " ";
  40. }
  41. return 0;
  42. }
  43. /******************************************************************************/
  44. int BubbleSort(int numbers[], int elements)
  45. {
  46. bool swap;
  47. int hold;
  48. int swapCount = 0;
  49.  
  50. do
  51. {
  52. // intialize flag
  53. swap = false;
  54.  
  55. //search elements
  56. for (int i = 0; i < (elements - 1); i++)
  57. {
  58. if(numbers[i] > numbers[i+1])
  59. {
  60. hold = numbers[i];
  61. numbers[i] = numbers[i+1];
  62. numbers[i+1] = hold;
  63. swap = true;
  64.  
  65. //increment swap counter
  66. swapCount++;
  67. }
  68. }
  69. }
  70. // while false
  71. while (swap);
  72.  
  73. return swapCount;
  74. }
  75. /******************************************************************************/
  76. int SelectionSort(int numbers[], int elements)
  77. {
  78. int start;
  79. int minIndex;
  80. int minValue;
  81. int sortCount;
  82.  
  83. for(start = 0; start < (elements-1); start++)
  84. {
  85. minIndex = start;
  86. minValue = numbers[start];
  87.  
  88. for(int i = start + 1; i < elements; i++)
  89. {
  90. if (numbers[i] < minValue)
  91. {
  92. minValue = numbers[i];
  93. minIndex = i;
  94.  
  95. }
  96. }
  97. numbers[minIndex] = numbers[start];
  98. numbers[start] = minValue;
  99.  
  100. sortCount++;
  101. }
  102. return sortCount;
  103. }
Success #stdin #stdout 0s 5268KB
stdin
Standard input is empty
stdout
103
1 2 3 4 5 6 7 8 9 10 11 12 13 14 14 15 16 17 19 20 
19
1 2 3 4 5 6 7 8 9 10 11 12 13 14 14 15 16 17 19 20