เรามีรายการ L โดยมีองค์ประกอบ n รายการ เราต้องตรวจสอบก่อนว่ารายการจะเรียงเป็นคู่หรือไม่ สมมติว่ารายการเป็นเหมือน {8, 10, 18, 20, 5, 15} นี่คือการเรียงลำดับคู่เป็น (8, 10), (18, 20), (5, 15) ถูกจัดเรียง หากรายการมีจำนวนองค์ประกอบคี่ รายการสุดท้ายจะถูกละเว้น
วิธีการนั้นง่ายเกินไป ให้ข้ามผ่านตัวเลขจากซ้ายไปขวา นำอิลิเมนต์สองตัวที่ต่อเนื่องกันมา และตรวจสอบว่ามีการเรียงลำดับหรือไม่ ถ้าคู่ใดไม่ถูกจัดเรียง ให้คืนค่าเท็จ หากไม่พบคู่ที่ไม่เรียงลำดับ ให้คืนค่าจริง
ตัวอย่าง
#include <iostream>
#include <cmath>
using namespace std;
class Node{
public:
int data;
Node *next;
};
void append(struct Node** start, int key) {
Node* new_node = new Node;
new_node->data = key;
new_node->next = (*start);
(*start) = new_node;
}
bool isPairwiseSorted(Node *start) {
bool flag = true;
struct Node* temp = start;
while (temp != NULL && temp->next != NULL) {
if (temp->data < temp->next->data) {
flag = false;
break;
}
temp = temp->next->next;
}
return flag;
}
int main() {
Node *start = NULL;
int arr[] = {8, 10, 18, 20, 5, 15};
int n = sizeof(arr)/sizeof(arr[0]);
for(int i = 0; i<n; i++){
append(&start, arr[i]);
}
if(isPairwiseSorted(start)){
cout << "This is pairwise sorted";
} else {
cout << "This is not pairwise sorted";
}
} ผลลัพธ์
This is pairwise sorted