Advertisement
Zuhairy_Harry

Merge Sort Khai

Jan 10th, 2024
1,136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. // Merge Sort
  2. void merge(Book catalog[], int left, int middle, int right) {
  3.     int n1 = middle - left + 1;
  4.     int n2 = right - middle;
  5.  
  6.     // Create temporary arrays
  7.     Book* leftArray = new Book[n1];
  8.     Book* rightArray = new Book[n2];
  9.  
  10.     // Copy data to temporary arrays leftArray[] and rightArray[]
  11.     for (int i = 0; i < n1; i++)
  12.         leftArray[i] = catalog[left + i];
  13.     for (int j = 0; j < n2; j++)
  14.         rightArray[j] = catalog[middle + 1 + j];
  15.  
  16.     // Merge the temporary arrays back into catalog[left..right]
  17.     int i = 0;
  18.     int j = 0;
  19.     int k = left;
  20.     while (i < n1 && j < n2) {
  21.         if (leftArray[i].bookID <= rightArray[j].bookID) {
  22.             catalog[k] = leftArray[i];
  23.             i++;
  24.         }
  25.         else {
  26.             catalog[k] = rightArray[j];
  27.             j++;
  28.             // Increment the total swaps counter for Merge Sort
  29.             totalSwapsMergeSort++;
  30.         }
  31.         k++;
  32.     }
  33.  
  34.     // Copy the remaining elements of leftArray[], if there are any
  35.     while (i < n1) {
  36.         catalog[k] = leftArray[i];
  37.         i++;
  38.         k++;
  39.     }
  40.  
  41.     // Copy the remaining elements of rightArray[], if there are any
  42.     while (j < n2) {
  43.         catalog[k] = rightArray[j];
  44.         j++;
  45.         k++;
  46.     }
  47.  
  48.     // Release allocated memory for temporary arrays
  49.     delete[] leftArray;
  50.     delete[] rightArray;
  51. }
  52.  
  53. // Merge Sort
  54. void mergeSort(Book catalog[], int left, int right) {
  55.     if (left < right) {
  56.         // Same as (left + right) / 2, but avoids overflow for large left and right
  57.         int middle = left + (right - left) / 2;
  58.  
  59.         // Sort first and second halves
  60.         mergeSort(catalog, left, middle);
  61.         mergeSort(catalog, middle + 1, right);
  62.  
  63.         // Merge the sorted halves
  64.         merge(catalog, left, middle, right);
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement