Home »
Data Structure
Check if a given array is pair wise sorted or not
Here is the program to check if a given array is pair wise sorted or not using C:
C program to check if a given array is pair wise sorted or not
#include <stdbool.h>
#include <stdio.h>
bool checkPairwiseSorted(int arr[], int size) {
for (int i = 0; i < size - 1; i += 2) {
if (arr[i] > arr[i + 1]) {
return false;
}
}
return true;
}
int main() {
int arr1[] = {10, 20, 30, 40, 50, 60};
int arr_size1 = sizeof(arr1) / sizeof(arr1[0]);
int arr2[] = {20, 10, 30, 50, 60, 40};
int arr_size2 = sizeof(arr2) / sizeof(arr2[0]);
if (checkPairwiseSorted(arr1, arr_size1)) {
printf("Array (arr1) is pair-wise sorted.\n");
} else {
printf("Array (arr1) is not pair-wise sorted.\n");
}
if (checkPairwiseSorted(arr2, arr_size2)) {
printf("Array (arr2) is pair-wise sorted.\n");
} else {
printf("Array (arr2) is not pair-wise sorted.\n");
}
return 0;
}
Output
Array (arr1) is pair-wise sorted.
Array (arr2) is not pair-wise sorted.