
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
#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
- Related Articles
- Check if a Linked List is Pairwise Sorted in C++
- Check if an array is descending, ascending or not sorted in JavaScript
- Check if list is sorted or not in Python
- Check if a binary tree is sorted levelwise or not in C++
- Program to check if an array is sorted or not (Iterative and Recursive) in C
- Check if the elements of stack are pairwise sorted in Python
- Check if a binary tree is sorted level-wise or not in C++
- Check if a given graph is tree or not
- Write a Golang program to check whether a given array is sorted or not (Using Bubble Sort Technique)
- Check if a given matrix is sparse or not in C++
- Check if a given number is sparse or not in C++
- Check if a given matrix is Hankel or not in C++
- Check if a number is in given base or not in C++
- Check if a given tree graph is linear or not in C++
- Python - Check if a given string is binary string or not

Advertisements