fork download
  1. // Nathanael Schwartz CS1A Chapter 8, P. 515, #9
  2. //
  3. /*******************************************************************************
  4.  *
  5.  * BUBBLE SORT AND SELECTION SORT WITH EXCHANGE COUNTS
  6.  * _____________________________________________________________________________
  7.  * This program uses two identical arrays of integers, sorts one using the bubble
  8.  * sort algorithm and the other using the selection sort algorithm. The program
  9.  * keeps a count of the number of exchanges made by each sorting algorithm.
  10.  * _____________________________________________________________________________
  11.  * INPUT
  12.  * arr1 : Array to be sorted using bubble sort
  13.  * arr2 : Array to be sorted using selection sort
  14.  *
  15.  * OUTPUT
  16.  * bubbleExchanges : Number of exchanges made by the bubble sort
  17.  * selectionExchanges : Number of exchanges made by the selection sort
  18.  *
  19.  ******************************************************************************/
  20. #include <iostream>
  21. using namespace std;
  22.  
  23. // Bubble Sort function
  24. void bubbleSort(int arr[], int size, int &exchangeCount) {
  25. for (int i = 0; i < size - 1; ++i) {
  26. for (int j = 0; j < size - i - 1; ++j) {
  27. if (arr[j] > arr[j + 1]) {
  28. // Swap and count the exchange
  29. swap(arr[j], arr[j + 1]);
  30. ++exchangeCount;
  31. }
  32. }
  33. }
  34. }
  35.  
  36. // Selection Sort function
  37. void selectionSort(int arr[], int size, int &exchangeCount) {
  38. for (int i = 0; i < size - 1; ++i) {
  39. int minIndex = i;
  40. for (int j = i + 1; j < size; ++j) {
  41. if (arr[j] < arr[minIndex]) {
  42. minIndex = j;
  43. }
  44. }
  45. // Swap and count the exchange
  46. if (minIndex != i) {
  47. swap(arr[i], arr[minIndex]);
  48. ++exchangeCount;
  49. }
  50. }
  51. }
  52.  
  53. int main() {
  54. // Initialize two identical arrays of integers
  55. int arr1[20] = {12, 3, 5, 7, 19, 2, 13, 18, 8, 4, 14, 1, 6, 15, 11, 17, 9, 20, 10, 16};
  56. int arr2[20] = {12, 3, 5, 7, 19, 2, 13, 18, 8, 4, 14, 1, 6, 15, 11, 17, 9, 20, 10, 16};
  57.  
  58. int bubbleExchanges = 0;
  59. int selectionExchanges = 0;
  60.  
  61. // Perform bubble sort on the first array and count exchanges
  62. bubbleSort(arr1, 20, bubbleExchanges);
  63.  
  64. // Perform selection sort on the second array and count exchanges
  65. selectionSort(arr2, 20, selectionExchanges);
  66.  
  67. // Display the results
  68. cout << "Bubble Sort Exchange Count: " << bubbleExchanges << endl;
  69. cout << "Selection Sort Exchange Count: " << selectionExchanges << endl;
  70.  
  71. return 0;
  72. }
  73.  
  74.  
  75.  
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
Bubble Sort Exchange Count: 72
Selection Sort Exchange Count: 16