Advertisement
Zuhairy_Harry

Merge Sort AA Project

Jan 11th, 2024
917
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. void merge(vector<Student>& students, int low, int mid, int high, int& swapCount) {
  2.     // ... (constant time operations)
  3.  
  4.     for (int i = 0; i < n1; i++)
  5.         left[i] = students[low + i];  // O(n1) - copying elements to left array
  6.     for (int j = 0; j < n2; j++)
  7.         right[j] = students[mid + 1 + j];  // O(n2) - copying elements to right array
  8.  
  9.     int i = 0, j = 0, k = low;
  10.  
  11.     while (i < n1 && j < n2) {
  12.         if (left[i].id <= right[j].id) {
  13.             students[k++] = left[i++];  // O(1) - copying element from left to students
  14.         } else {
  15.             students[k++] = right[j++];
  16.             swapCount += n1 - i;  // O(1) - counting swaps when elements are moved from left to right
  17.         }
  18.     }
  19.  
  20.     while (i < n1) {
  21.         students[k++] = left[i++];  // O(1) - copying remaining elements from left to students
  22.     }
  23.     while (j < n2) {
  24.         students[k++] = right[j++];  // O(1) - copying remaining elements from right to students
  25.     }
  26. }
  27.  
  28. void mergeSort(vector<Student>& students, int low, int high, int& swapCount) {
  29.     if (low < high) {
  30.         int mid = low + (high - low) / 2;
  31.  
  32.         mergeSort(students, low, mid, swapCount);   // T(n/2) - recursive call on left half
  33.         mergeSort(students, mid + 1, high, swapCount);  // T(n/2) - recursive call on right half
  34.  
  35.         merge(students, low, mid, high, swapCount);  // O(n) - merging two sorted halves
  36.     }
  37.     // Base case: if low >= high, no work is done
  38. }
  39.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement