Guest User

Untitled

a guest
Jun 25th, 2018
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.11 KB | None | 0 0
  1. /*
  2.  *  Also sorts
  3.  */
  4. void mergeSort(int * list, int low, int high)
  5. {
  6.     assert(low <= high);
  7.     if (high - low == 1) return;
  8.  
  9.     int mid = (high - low) / 2, // Middle of the list.
  10.         p = low,                // Point for the original list
  11.         lp = 0,                 // Pointer for left list
  12.         rp = 0,                 // Pointer for right list
  13.         ln = mid - low,         // Length of left list
  14.         rn = high - mid;        // Length of right list
  15.  
  16.     assert(mid - low + high - mid == high - low);
  17.  
  18.     int * left = new int[ln];
  19.     int * right = new int[rn];
  20.    
  21.     // Populate left and right lists
  22.     while (lp < ln)
  23.         left[lp++] = list[p++];
  24.     while (rp < rn)
  25.         right[rp++] = list[p++];
  26.    
  27.     // Recursively call mergesort on left - right
  28.     mergeSort(left, 0, mid);
  29.     mergeSort(right, 0, high - mid);
  30.  
  31.     // reset pointers
  32.     p = low;
  33.     lp = 0;
  34.     rp = 0;
  35.  
  36.     // Merge left and right
  37.     while (lp < ln || rp < rn)
  38.     {
  39.         if (lp < ln && rp < rn)
  40.         {
  41.             if (left[lp] <= right[rp])
  42.                 list[p++] = left[lp++];
  43.             else
  44.                 list[p++] = right[rp++];
  45.            
  46.         }
  47.         else if (lp < ln)
  48.             list[p++] = left[lp++];
  49.         else
  50.             list[p++] = right[rp++];
  51.     }
  52.  
  53.     delete [] left;
  54.     delete [] right;
  55. }
Add Comment
Please, Sign In to add comment