Advertisement
RK-Coder

AS_1

Mar 26th, 2023
900
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.26 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. int IsLargeApples(int i, int j); // function to compare sizes of apples
  6.  
  7. void mergeSort(vector<int>& A, vector<int>& S, int left, int right) {
  8.     if (left >= right) return;
  9.     int mid = left + (right - left) / 2;
  10.     mergeSort(A, S, left, mid);
  11.     mergeSort(A, S, mid + 1, right);
  12.     vector<int> temp(right - left + 1);
  13.     int i = left, j = mid + 1, k = 0;
  14.     while (i <= mid && j <= right) {
  15.         if (IsLargeApples(A[S[i]], A[S[j]]) == -1) {
  16.             temp[k++] = S[i++];
  17.         } else {
  18.             temp[k++] = S[j++];
  19.         }
  20.     }
  21.     while (i <= mid) temp[k++] = S[i++];
  22.     while (j <= right) temp[k++] = S[j++];
  23.     for (int p = 0; p < k; p++) {
  24.         S[left + p] = temp[p];
  25.     }
  26. }
  27.  
  28. vector<int> sortApples(vector<int>& A) {
  29.     int n = A.size();
  30.     vector<int> S(n);
  31.     for (int i = 0; i < n; i++) {
  32.         S[i] = i; // initialize S with indices of A
  33.     }
  34.     mergeSort(A, S, 0, n - 1);
  35.     return S;
  36. }
  37.  
  38. int main() {
  39.     vector<int> A = {5, 2, 7, 3, 9, 1, 8, 6, 4};
  40.     vector<int> S = sortApples(A);
  41.     cout << "Sorted indices of apples: ";
  42.     for (int i = 0; i < S.size(); i++) {
  43.         cout << S[i] << " ";
  44.     }
  45.     cout << endl;
  46.     return 0;
  47. }
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement