มี Array A ขนาด n ต้องตรวจสอบว่า Pairwise Sorted หรือไม่ ตัวอย่าง {8, 10, 18, 20, 5, 15} เป็น Pairwise Sorted เพราะ (8,10), (18,20), (5,15) เรียงลำดับ ถ้า Array มี Odd Elements ตัวสุดท้ายจะถูก Ignore
วิธีง่าย: Loop i จาก 0 ถึง n-1 Step 2 เช็ค arr[i] <= arr[i+1] มิฉะนั้น false
ตัวอย่างโค้ด C++
#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