Tuesday, 26 Oct 2021

# Check if an array of pairs can be sorted by swapping pairs with different first elements

Check if an array of pairs can be sorted by swapping pairs with different first elementsGiven an array arr[] consisting of N pairs, where each pair represents the value and ID respectively, the task is to check if it is possible to sort the array by the first element by swapping only pairs having different IDs. If it is possible to sort, then print “Yes”. Otherwise, print “No”.Examples:Input: arr[] = {{340000, 2}, {45000, 1}, {30000, 2}, {50000, 4}}Output: YesExplanation:One of the possible way to sort the array is to swap the array elements in the following order:Swap, arr and arr, which modifies the array to arr[] = {{50000, 4}, {45000, 1}, {30000, 2}, {340000, 2}}.Swap, arr and arr, which modifies the array to arr[] = {{30000, 2}, {45000, 1}, {50000, 4}, {340000, 2}}.Therefore, after the above steps the given array is sorted by the first element..Input: arr[] = {{15000, 2}, {34000, 2}, {10000, 2}}Output: NoApproach: The given problem can be solved based on the observation that the array can be sorted if there exist any two array elements with different IDs. Follow the steps below to solve the problem:Initialize a variable, say X that stores the ID of the pair at index 0.Traverse the array arr[] and if there exists any pair whose ID is different from X, then print “Yes” and break out of the loop.After completing the above steps, if all the elements have the same IDs and if the array is already sorted then print “Yes”. Otherwise, Print “No”.Below is the implementation of the above approach:C++  #include using namespace std;  bool isSorted(pair* arr,              int N){        for (int i = 1; i < N; i++) {          if (arr[i].first            > arr[i – 1].first) {            return false;        }    }          return true;}  string isPossibleToSort(    pair* arr, int N){        int group = arr.second;          for (int i = 1; i < N; i++) {                          if (arr[i].second != group) {            return "Yes";        }    }          if (isSorted(arr, N)) {        return "Yes";    }    else {        return "No";    }}  int main(){    pair arr[]        = { { 340000, 2 }, { 45000, 1 },             { 30000, 2 }, { 50000, 4 } };      int N = sizeof(arr) / sizeof(arr);      cout