fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. void fill_array(int a[ ], int size, int& number_used);
  5.  
  6.  
  7. void sort(int a[ ], int number_used);
  8.  
  9.  
  10. void swap_values(int& v1, int& v2);
  11. //Interchanges the values of v1 and v2.
  12.  
  13. int index_of_smallest(const int a[ ], int start_index, int number_used);
  14.  
  15.  
  16. int main( )
  17. {
  18. cout << "Program to sort numbers in ascending order.\n";
  19.  
  20. int sample_array[10], number_used;
  21. fill_array(sample_array, 10, number_used);
  22. sort(sample_array, number_used);
  23.  
  24. cout << "In sorted order the numbers are:\n";
  25. for (int index = 0; index < number_used; index++)
  26. cout << sample_array[index] << " ";
  27. cout << endl;
  28.  
  29. return 0;
  30. }
  31.  
  32. //Uses iostream:
  33. void fill_array(int a[ ], int size, int& number_used)
  34. {
  35. cout << "Enter up to " << size << " nonnegative whole numbers.\n"
  36. << "Mark the end of the list with a negative number.\n";
  37.  
  38. int next, index = 0;
  39. cin >> next;
  40. while ((next >= 0) && (index < size))
  41. {
  42. a[index] = next;
  43. index++;
  44. cin >> next;
  45. }
  46.  
  47. number_used = index;
  48. }
  49.  
  50. void sort(int a[ ], int number_used)
  51. {
  52. int index_of_next_smallest;
  53. for (int index = 0; index < number_used - 1; index++)
  54. {
  55. //Place the correct value in a[index]:
  56. index_of_next_smallest = index_of_smallest(a, index, number_used);
  57. swap_values(a[index], a[index_of_next_smallest]);
  58. //a[0] <= a[1] <=...<= a[index] are the smallest of the original array
  59. //elements. The rest of the elements are in the remaining positions.
  60. }
  61. }
  62.  
  63. void swap_values(int& v1, int& v2)
  64. {
  65. int temp;
  66. temp = v1;
  67. v1 = v2;
  68. v2 = temp;
  69. }
  70.  
  71.  
  72. int index_of_smallest(const int a[ ], int start_index, int number_used)
  73. {
  74. int min = a[start_index],
  75. index_of_min = start_index;
  76. for (int index = start_index + 1; index < number_used; index++)
  77. if (a[index] < min)
  78. {
  79. min = a[index];
  80. index_of_min = index;
  81. //min is the smallest of a[start_index] through a[index]
  82. }
  83.  
  84. return index_of_min;
  85. }
  86.  
Success #stdin #stdout 0s 2688KB
stdin
6 8 23 34 12 2 4 65 -3
stdout
Program to sort numbers in ascending order.
Enter up to 10 nonnegative whole numbers.
Mark the end of the list with a negative number.
In sorted order the numbers are:
2 4 6 8 12 23 34 65