我们有一个数组A,其中包含n个元素。我们必须检查数组是否成对排序。假设数组像{8,10,18,20,5,15}。这是成对排序的,因为(8,10),(18,20),(5,15)被排序。如果数组中元素的数量为奇数,则最后一个元素将被忽略。
方法太简单了,通过将I从0设为n-1,我们将看到第ith个元素是否小于第i + 1元素,如果不小于,则返回false,否则将I增加2。
#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"; } }
输出结果
This is pairwise sorted