ได้รับอาร์เรย์สมาชิกต่างกันและไม่เรียงลำดับ ต้องการนับ "เส้นข้าม" หลังจากเรียงลำดับแล้ว เส้นข้ามคือจำนวนคู่ที่สลับตำแหน่งกันเมื่อเรียงลำดับ (inversion count)
ตัวอย่าง
อินพุต: arr[] = {4, 3, 1, 2}
เอาต์พุต: 5
อินพุต: arr[] = {0, 1, 5, 3}
เอาต์พุต: 1
แนวทาง: ใช้ Insertion Sort
- นับจำนวนครั้งที่เลขถูกเลื่อนผ่านค่าที่มากกว่ามัน (shift)
- แต่ละ shift = 1 เส้นข้าม
- รวม shifts ทั้งหมด = จำนวน inversion = จำนวนเส้นข้าม
ตัวอย่างโค้ด C++
#include <bits/stdc++.h>
using namespace std;
int insertionSort(int arr[], int n) {
int count = 0;
for (int i = 1; i < n; i++) {
int item = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > item) {
arr[j + 1] = arr[j];
j = j - 1;
count++;
}
arr[j + 1] = item;
}
return count;
}
int main() {
int arr[] = {4, 5, 3, 1, 2};
int n = 5;
cout << "Number of cross lines: " << insertionSort(arr, n);
return 0;
}
ผลลัพธ์
Number of cross lines: 8