Horje
PHP Program For Counting Inversions In An Array - Set 1 (Using Merge Sort)

Inversion Count for an array indicates – how far (or close) the array is from being sorted. If the array is already sorted, then the inversion count is 0, but if the array is sorted in the reverse order, the inversion count is the maximum. 
Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j.

Examples: 

Input: arr[] = {8, 4, 2, 1}
Output: 6
Explanation: Given array has six inversions:
(8, 4), (4, 2), (8, 2), (8, 1), (4, 1), (2, 1).

Input: arr[] = {3, 1, 2}
Output: 2
Explanation: Given array has two inversions: (3, 1), (3, 2) 

Simple Method  

Traverse through the array, and for every index, find the number of smaller elements on it’s right side of the array. This can be done using a nested loop. Sum up the counts for all index in the array and print the sum.

Algorithm

  • Traverse through the array from start to end
  • For every element, find the count of elements smaller than the current number up to that index using another loop.
  • Sum up the count of inversion for every index.
  • Print the count of inversions.

Implementation

PHP
<?php 
// PHP program to Count Inversions
// in an array

function getInvCount(&$arr, $n) {
    $inv_count = 0;
    for ($i = 0; $i < $n - 1; $i++)
        for ($j = $i + 1; $j < $n; $j++)
            if ($arr[$i] > $arr[$j])
                $inv_count++;

    return $inv_count;
}

// Driver Code
$arr = array(1, 20, 6, 4, 5 );
$n = sizeof($arr);

echo "Number of inversions are " . getInvCount($arr, $n);

?>

Output
Number of inversions are 5

Complexity Analysis

  • Time Complexity: O(n^2), Two nested loops are needed to traverse the array from start to end, so the Time complexity is O(n^2)
  • Space Complexity:O(1), No extra space is required.

Please refer complete article on Count Inversions in an array | Set 1 (Using Merge Sort) for more details!




Reffered: https://www.geeksforgeeks.org


Arrays

Related
Maximize subarray sum by inverting sign of elements of any subarray at most twice Maximize subarray sum by inverting sign of elements of any subarray at most twice
Find the sum between given cells of a 3D Array Find the sum between given cells of a 3D Array
Maximize remainder difference between two pairs in given Array Maximize remainder difference between two pairs in given Array
Minimize swaps required to make all prime-indexed elements as prime Minimize swaps required to make all prime-indexed elements as prime
Minimum size of subset of pairs whose sum is at least the remaining array elements Minimum size of subset of pairs whose sum is at least the remaining array elements

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
11