fork download
  1. //Xinnuo Wanng CS1A Chapter 8 #10 Page.489
  2. /*******************************************************************************
  3.  * Sort Arrays
  4.  * _____________________________________________________________________________
  5.  * The program uses two identical arrays of just eight integers, displays the
  6.  * first and second arrays, sorts the first array using bubble sort, sorts
  7.  * the other using selection sort, and print out the array contents after each
  8.  * pass of the sort.
  9.  * _____________________________________________________________________________
  10.  * Input
  11.  * num : The number
  12.  *
  13.  * ****************************************************************************/
  14. #include <iostream>
  15. using namespace std;
  16. void bubble(int arr[], int size);
  17. void selection (int arr2[],int size);
  18. void swap(int &a, int & b);
  19. void print (int arr[],int size);
  20. int main()
  21. {
  22. int arr[]={27, 11, 99, 888, 666, 999,776, 0 };
  23. int size = sizeof(arr)/sizeof(arr[0]);
  24. int arr2[size];
  25. for (int i = 0;i< size; i++)
  26. {
  27. arr2[i]= arr[i];
  28. cout << arr[i]<<" ";
  29. }
  30. cout << endl;
  31. bubble(arr, size);
  32. print (arr,size);
  33. cout << endl;
  34. selection(arr2,size);
  35. print (arr2,size);
  36. cout << endl;
  37. return 0;
  38. }
  39. void bubble(int arr[], int size)
  40. {
  41. for(int i = size-1;i > 0; i--)
  42. {
  43. for(int j = 0; j < i; j++)
  44. {
  45. if(arr[j]>arr[j+1])
  46. {
  47. swap(arr[j],arr[j+1]);
  48. }
  49. }
  50. }
  51. }
  52. void selection (int arr2[],int size)
  53. {
  54. for (int start = 0; start < size; start++)
  55. {
  56. int minIndex = start;
  57. for (int i = start +1; i< size; i ++)
  58. {
  59. if (arr2[i]< arr2[minIndex])
  60. {
  61. minIndex =i;
  62. }
  63. }
  64. swap(arr2[minIndex], arr2[start] );
  65. }
  66. }
  67. void print (int arr[],int size)
  68. {
  69. for(int i = 0; i< size; i++)
  70. {
  71. cout << arr[i]<<" ";
  72. }
  73. }
  74. void swap (int &a, int & b)
  75. {
  76. int temp = a;
  77. a=b;
  78. b = temp;
  79. }
Success #stdin #stdout 0s 5344KB
stdin
Standard input is empty
stdout
27 11 99 888 666 999 776 0 
0 11 27 99 666 776 888 999 
0 11 27 99 666 776 888 999