Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP program to Count Inversions of size three in a given array
Inversion count is a measure that determines how far an array is from being sorted. For inversions of size three, we look for triplets (i, j, k) where a[i] > a[j] > a[k] and i . This helps analyze the sorting complexity of an array.
Array: {5, 4, 3, 2, 1} // reverse order
Triplets: (5,4,3), (5,4,2), (5,4,1), (5,3,2), (5,3,1), (5,2,1), (4,3,2), (4,3,1), (4,2,1), (3,2,1)
Output: 10
Array: {1, 2, 3, 4, 5} // ascending order
Triplets: None
Output: 0
Array: {8, 4, 2, 1}
Triplets: (8,4,2), (8,4,1), (8,2,1), (4,2,1)
Output: 4
Algorithm
The basic approach considers each element as the middle element of a potential inversion triplet ?
Step 1 For each middle element, count smaller elements on the right
Step 2 Count greater elements on the left
Step 3 Multiply both counts and add to result
Step 4 Return total inversion count
Simple Approach (O(n²))
This method treats each element as the middle of a triplet and counts valid combinations ?
<?php
function countInversions($arr, $n) {
$invCount = 0;
// Consider each element as middle element
for ($i = 1; $i < $n - 1; $i++) {
$smaller = 0; // Count smaller elements on right
for ($j = $i + 1; $j < $n; $j++) {
if ($arr[$i] > $arr[$j]) {
$smaller++;
}
}
$greater = 0; // Count greater elements on left
for ($j = $i - 1; $j >= 0; $j--) {
if ($arr[$i] < $arr[$j]) {
$greater++;
}
}
$invCount += $greater * $smaller;
}
return $invCount;
}
$arr = array(8, 4, 2, 1);
$n = sizeof($arr);
echo "Inversion Count: " . countInversions($arr, $n);
?>
Inversion Count: 4
Example with Different Array
Let's test with another array to see how the algorithm works ?
<?php
function countInversions($arr, $n) {
$invCount = 0;
for ($i = 1; $i < $n - 1; $i++) {
$smaller = 0;
for ($j = $i + 1; $j < $n; $j++) {
if ($arr[$i] > $arr[$j]) {
$smaller++;
}
}
$greater = 0;
for ($j = $i - 1; $j >= 0; $j--) {
if ($arr[$i] < $arr[$j]) {
$greater++;
}
}
$invCount += $greater * $smaller;
}
return $invCount;
}
$arr = array(9, 6, 4, 5, 8);
$n = sizeof($arr);
echo "Array: [" . implode(", ", $arr) . "]
";
echo "Inversion Count of Size 3: " . countInversions($arr, $n);
?>
Array: [9, 6, 4, 5, 8] Inversion Count of Size 3: 2
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Simple Method | O(n²) | O(1) |
| Binary Indexed Tree | O(n log n) | O(n) |
Conclusion
Counting inversions of size three helps analyze array disorder patterns. The simple O(n²) approach works well for moderate-sized arrays by treating each element as a potential middle element of triplets.
