fork(4) download
  1. #include <iostream>
  2.  
  3. void sort (int *array, int low, int high) {
  4. //Insertion sort
  5. for (int i = low; i < high; i++) {
  6. for (int j = i - 1; j >= low; j--) {
  7. if (array[i] < array [j]) {
  8. int holder = array[j];
  9. array[j] = array[i];
  10. array[i] = holder;
  11. i--;
  12. }
  13. }
  14. }
  15. }
  16. void merge (int *array, int *sub, int low, int mid, int high) {
  17. //Merge part of mergesort
  18. int a = low;
  19. int b = low;
  20. int c = mid;
  21.  
  22. while ((a < mid) && (c < high)) {
  23. if (array[a] <= array[c]) {
  24. sub[b] = array[a];
  25. a++;
  26. } else {
  27. sub[b] = array[c];
  28. c++;
  29. }
  30. b++;
  31. }
  32. while (a == mid && c < high) {
  33. sub[b] = array[c];
  34. c++;
  35. b++;
  36. }
  37. while (c == high && a < mid) {
  38. sub[b] = array[a];
  39. a++;
  40. b++;
  41. }
  42. for (int d = low; d < high; d++) {
  43. array[d] = sub[d];
  44. }
  45. }
  46. void split (int *array, int *sub, int low, int high) {
  47. //Split part of mergesort
  48. if (low < high - 1) {
  49. int mid = (low + high) / 2;
  50. split(array, sub, low, mid);
  51. split(array, sub, mid, high);
  52. if ((high - low) > 10){
  53. merge(array, sub, low, mid, high);
  54. } else {
  55. sort(array, low, high);
  56. }
  57.  
  58. }
  59. }
  60.  
  61. int main()
  62. {
  63. std::cout << "This is a program that sorts integers.\n";
  64. std::cout << "How many numbers would you like to sort?\n";
  65. int num;
  66. std::cin >> num;
  67. if (num < 0) {
  68. std::cout << "Invalid amount of numbers.\n";
  69. return 0;
  70. } else if (num == 0) {
  71. std::cout << "No numbers to sort.\n";
  72. return 0;
  73. } else if (num == 1) {
  74. std::cout << "Please type in the number.\n";
  75. std::cin >> num;
  76. std::cout << "Your sorted number is: " << num << ".\n";
  77. return 0;
  78. }
  79. int * array = new int [num];
  80. int * sub = new int [num];
  81. std::cout << "Please type in the numbers.\n";
  82. for (int i = 0; i < num; i++) {
  83. std::cin >> array[i];
  84. }
  85. split(array, sub, 0, num);
  86. std::cout << "Your sorted numbers are: ";
  87. for (int i = 0; i < num; i++) {
  88. std::cout << array[i];
  89. if (i != num - 1) {
  90. std::cout << ", ";
  91. } else {
  92. std::cout << ".\n";
  93. }
  94. }
  95. delete[] array;
  96. delete[] sub;
  97.  
  98. return 0;
  99.  
  100. }
Success #stdin #stdout 0s 3480KB
stdin
22
9
1
1
4
4
0
3
8
5
7
9
5
9
1
3
3
1
5
7
0
7
2
stdout
This is a program that sorts integers.
How many numbers would you like to sort?
Please type in the numbers.
Your sorted numbers are: 0, 0, 1, 1, 1, 1, 2, 3, 3, 3, 4, 4, 5, 5, 5, 7, 7, 7, 8, 9, 9, 9.