fork download
  1. //Xinnuo Wanng CS1A Chapter 8 #9 Page.488
  2. /*******************************************************************************
  3.  * Sort Arrays
  4.  * _____________________________________________________________________________
  5.  * The program uses two arrays of at least 20 integers.One calling uses bubble
  6.  * sort and the other uses selection sort. Both of them need to count the number
  7.  * of exchanges.
  8.  * _____________________________________________________________________________
  9.  * Input
  10.  * num1 : The number of exchange in bubble sort.
  11.  * num2 : The number of exchange in selection sort.
  12.  *
  13.  * ****************************************************************************/
  14.  
  15. #include <iostream>
  16. using namespace std;
  17. void bubble(int arr[], int size);
  18. void selection (int arr2[], int size2);
  19. void swap (int & a, int &b);
  20. void print(int arr[],int size);
  21.  
  22. int main()
  23. {
  24. int arr[]={26791, 33445, 79422, 13579,93121,62483, 55555,
  25. 77777, 85647, 26793};
  26. int size = sizeof(arr)/sizeof (arr[0]);
  27. bubble (arr,size);
  28. print (arr,size);
  29. cout<<endl;
  30. int arr2[]={
  31. 2341, 4523, 22, 3412, 2711, 8999, 9999,8876, 6767, 2323, 9922,1111
  32. };
  33. int size2 = sizeof(arr2)/sizeof (arr2[0]);
  34. selection(arr2, size2);
  35. print(arr2,size2);
  36.  
  37.  
  38. return 0;
  39. }
  40. void bubble(int arr[], int size)
  41. {
  42. for (int i = size-1; i > 0; i--)
  43. {
  44. for (int j= 0; j < i; j++)
  45. {
  46. if (arr[j]>arr[j+1])
  47. {
  48. swap (arr[j],arr[j+1]);
  49. }
  50. }
  51. }
  52. }
  53. void selection (int arr2[], int size2)
  54. {
  55. for(int start = 0; start < size2; start ++)
  56. {
  57. int minIndex = start;
  58. for (int i =start+1; i <size2; i++)
  59. {
  60. if (arr2[minIndex]> arr2[i])
  61. {
  62. minIndex =i;
  63. }
  64. }
  65. swap(arr2[minIndex], arr2[start]);
  66. }
  67. }
  68. void print(int arr[],int size)
  69. {
  70. for(int i =0; i< size; i++)
  71. {
  72. cout << arr[i]<<" ";
  73. }
  74. }
  75. void swap (int &a, int & b)
  76. {
  77. int temp = a;
  78. a=b;
  79. b=temp;
  80. }
Success #stdin #stdout 0s 5332KB
stdin
Standard input is empty
stdout
13579 26791 26793 33445 55555 62483 77777 79422 85647 93121 
22 1111 2323 2341 2711 3412 4523 6767 8876 8999 9922 9999