Check if a given array is pairwise sorted or not in C++


We have an array A, with n elements. We have to check whether the array is pairwise sorted or not. Suppose the array is like {8, 10, 18, 20, 5, 15}. This is pairwise sorted as (8, 10), (18, 20), (5, 15) are sorted. If the array has an odd number of elements, then the last one will be ignored.

The approach is too simple, by taking I from 0 to n-1, we will see if the ith element is less than the i+1th element or not, if not, then return false, otherwise increase I by 2.

Example

 Live Demo

#include <iostream>
#include <cmath>
using namespace std;
bool isPairwiseSorted(int arr[], int n) {
   if(n <= 1)
      return true;
   for(int i = 0; i<n; i += 2){
      if(arr[i] > arr[i + 1])
         return false;
   }
   return true;
}
int main() {
   int arr[] = {8, 10, 18, 20, 5, 15};
   int n = sizeof(arr)/sizeof(arr[0]);
   if(isPairwiseSorted(arr, n)){
      cout << "This is pairwise sorted";
   } else {
      cout << "This is not pairwise sorted";
   }
}

Output

This is pairwise sorted

Updated on: 21-Oct-2019

97 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements