Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1.  
  2. void merge(int* arr, int from, int middle, int to) {
  3.     int newSize = to - from + 1;
  4.     int* temp = new int[newSize];
  5.    
  6.     int firstIndex = from;
  7.     int secondIndex = middle + 1;
  8.     int tempIndex = 0;
  9.     while (firstIndex <= middle && secondIndex <= to) {
  10.         if (arr[firstIndex] < arr[secondIndex]) {
  11.             temp[tempIndex] = arr[firstIndex];
  12.             tempIndex++;
  13.             firstIndex++;
  14.         }
  15.         else {
  16.             temp[tempIndex] = arr[secondIndex];
  17.             tempIndex++;
  18.             secondIndex++;
  19.         }
  20.     }
  21.  
  22.     while (firstIndex <= middle) {
  23.         temp[tempIndex] = arr[firstIndex];
  24.         tempIndex++;
  25.         firstIndex++;
  26.     }
  27.     while (secondIndex <= to) {
  28.         temp[tempIndex] = arr[secondIndex];
  29.         tempIndex++;
  30.         secondIndex++;
  31.     }
  32.  
  33.     for (int copyIndex = from; copyIndex <= to; copyIndex++) {
  34.         arr[copyIndex] = temp[copyIndex - from];
  35.     }
  36.  
  37.     delete[] temp;
  38. }
  39.  
  40. void mergeSort(int* arr, int from, int to) {
  41.     if (to <= from) { // bottom of recursion
  42.         return;
  43.     }
  44.  
  45.     int middle = (from + to) / 2;
  46.     mergeSort(arr, from, middle);
  47.     mergeSort(arr, middle + 1, to);
  48.     merge(arr, from, middle, to);
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement