เรามีอาร์เรย์ A ที่มีองค์ประกอบ n เราต้องตรวจสอบว่าอาร์เรย์ถูกจัดเรียงแบบคู่หรือไม่ สมมติว่าอาร์เรย์เป็นเหมือน {8, 10, 18, 20, 5, 15} นี่คือการเรียงลำดับคู่เป็น (8, 10), (18, 20), (5, 15) ถูกจัดเรียง หากอาร์เรย์มีจำนวนองค์ประกอบคี่ ตัวสุดท้ายจะถูกละเว้น
วิธีการนั้นง่ายเกินไป โดยเอา I จาก 0 ถึง n-1 เราจะดูว่าองค์ประกอบ ith น้อยกว่าองค์ประกอบที่ i+1 หรือไม่ ถ้าไม่ ก็คืนค่าเท็จ มิฉะนั้น ให้เพิ่ม 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