Check if a given array is pairwise sorted or not

link 0

An array is considered pairwise sorted if each successive pair of numbers is in sorted (non-decreasing) order. In case of odd elements, last element is ignored and result is based on remaining even number of elements.


Input : arr[] = {10, 15, 9, 9, 1, 5};
Output : Yes
Pairs are (10, 15), (9,  9) and (1, 5).
All these pairs are sorted in non-decreasing

Input : arr[] = {10, 15, 8, 9, 10, 5};
Output : No
The last pair (10, 5) is not sorted.

The idea is to traverse array from left to right. Compare elements pairwise, if any pair violates property, we return false. If no pair violates property, we return false.

// CPP program to check if an array is pair wise
// sorted.
#include <bits/stdc++.h>
using namespace std;
// Check whether the array is pairwise sorted
// or not.
bool checkPairWiseSorted(int arr[], int n)
    if (n==0 || n==1)
        return true;
    for (int i=0; i<n; i += 2)
        if (arr[i] > arr[i+1])
            return false;
    return true;
// Driver program to test above function
int main()
   int arr[] = {2, 5, 3, 7, 9, 11};
   int n = sizeof(arr)/sizeof(arr[0]);  
   if (checkPairWiseSorted(arr,n))
   return 0;



Time Complexity: O(n)
Space Complexity: O(1)

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at #techcodebit #google #microsoft #facebook #interview portal #jobplacements


Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar