fork download
  1. // Marvyn Jesse De La Torre CS1A Chapter 8 #10 pg.489
  2. //
  3. /*************************************************************
  4. * Determine Sorting Orders
  5. *
  6. * This program accepts eight integers using bubble sort
  7. * and selection sort. It displays the array after each pass.
  8. *
  9. * Input:
  10. * Eight integers entered by the user
  11. *
  12. * Output:
  13. * Displays the original array and the results of each pass.
  14. *************************************************************/
  15.  
  16. #include <iostream>
  17. using namespace std;
  18.  
  19. void bubble(int arr[], int size);
  20. void selection(int arr[], int size);
  21. void print(int arr[], int size);
  22. void swap(int &a, int &b);
  23.  
  24. int main()
  25. {
  26. const int SIZE = 8;
  27. int arr[SIZE];
  28. int arr2[SIZE];
  29.  
  30. cout << "Enter eight numbers: ";
  31.  
  32. for (int i = 0; i < SIZE; i++)
  33. {
  34. cin >> arr[i];
  35. arr2[i] = arr[i];
  36. }
  37.  
  38. cout << endl << "Original array: ";
  39. print(arr, SIZE);
  40.  
  41. cout << endl << endl << "Bubble Sort:" << endl;
  42. bubble(arr, SIZE);
  43.  
  44. cout << endl << "Selection Sort:" << endl;
  45. selection(arr2, SIZE);
  46.  
  47. return 0;
  48. }
  49.  
  50. void bubble(int arr[], int size)
  51. {
  52. for (int i = size - 1; i > 0; i--)
  53. {
  54. for (int j = 0; j < i; j++)
  55. {
  56. if (arr[j] > arr[j + 1])
  57. {
  58. swap(arr[j], arr[j + 1]);
  59. }
  60. }
  61.  
  62. cout << "Pass: ";
  63. print(arr, size);
  64. cout << endl;
  65. }
  66. }
  67.  
  68. void selection(int arr[], int size)
  69. {
  70. for (int start = 0; start < size - 1; start++)
  71. {
  72. int minIndex = start;
  73.  
  74. for (int i = start + 1; i < size; i++)
  75. {
  76. if (arr[i] < arr[minIndex])
  77. {
  78. minIndex = i;
  79. }
  80. }
  81.  
  82. swap(arr[minIndex], arr[start]);
  83.  
  84. cout << "Pass: ";
  85. print(arr, size);
  86. cout << endl;
  87. }
  88. }
  89.  
  90. void print(int arr[], int size)
  91. {
  92. for (int i = 0; i < size; i++)
  93. {
  94. cout << arr[i] << " ";
  95. }
  96. }
  97.  
  98. void swap(int &a, int &b)
  99. {
  100. int temp = a;
  101. a = b;
  102. b = temp;
  103. }
Success #stdin #stdout 0s 5348KB
stdin
27 11 99 888 666 999 776 0
stdout
Enter eight numbers: 
Original array: 27 11 99 888 666 999 776 0 

Bubble Sort:
Pass: 11 27 99 666 888 776 0 999 
Pass: 11 27 99 666 776 0 888 999 
Pass: 11 27 99 666 0 776 888 999 
Pass: 11 27 99 0 666 776 888 999 
Pass: 11 27 0 99 666 776 888 999 
Pass: 11 0 27 99 666 776 888 999 
Pass: 0 11 27 99 666 776 888 999 

Selection Sort:
Pass: 0 11 99 888 666 999 776 27 
Pass: 0 11 99 888 666 999 776 27 
Pass: 0 11 27 888 666 999 776 99 
Pass: 0 11 27 99 666 999 776 888 
Pass: 0 11 27 99 666 999 776 888 
Pass: 0 11 27 99 666 776 999 888 
Pass: 0 11 27 99 666 776 888 999