Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. void merge(int* data, int low, int mid, int high)
  4. {
  5. int low_copy = low;
  6. int mid_copy = mid;
  7.  
  8. int size = high - low;
  9. int* sorted = new int[size];
  10. int i = 0;
  11.  
  12. while(low_copy < mid && mid_copy < high) {
  13. if(data[low_copy] < data[mid_copy]) {
  14. sorted[i] = data[low_copy++];
  15. }
  16. else {
  17. sorted[i] = data[mid_copy++];
  18. }
  19. ++i;
  20. }
  21.  
  22. while(low_copy < mid) {
  23. sorted[i++] = data[low_copy++];
  24. }
  25. while(mid_copy < high) {
  26. sorted[i++] = data[mid_copy++];
  27. }
  28.  
  29. for(i = 0; i < size; ++i) {
  30. data[low + i] = sorted[i];
  31. }
  32. }
  33.  
  34. void recursive_merge_sort(int* data, int low, int high) {
  35. if(low >= high - 1) { return; }
  36.  
  37. int mid = (high + low) / 2;
  38. recursive_merge_sort(data, low, mid);
  39. recursive_merge_sort(data, mid, high);
  40.  
  41. merge(data, low, mid, high);
  42. }
  43.  
  44. void merge_sort(int* data, int num_elements) {
  45. recursive_merge_sort(data, 0, num_elements);
  46. }
  47.  
  48. int main()
  49. {
  50. int data[] = { 5, 1, 4, 3, 65, 6, 128, 9, 0 };
  51. int num_elements = 9;
  52.  
  53. std::cout << "unsortedn";
  54. for(int i=0; i < num_elements; ++i) {
  55. std::cout << data[i] << " ";
  56. }
  57.  
  58. merge_sort(data, num_elements);
  59.  
  60. std::cout << "nsortedn";
  61. for(int i=0; i < num_elements; ++i) {
  62. std::cout << data[i] << " ";
  63. }
  64.  
  65. return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement