GFG App
Open App
Browser
Continue

# 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Â
Example:Â

```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) ```

METHOD (Simple):Â Â

Approach: Traverse through the array, and for every index, find the number of smaller elements on its 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:

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

Implementation:

## PHP

 ` ``\$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``); ` `// This code is contributed by ita_c ` `?>`

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!

My Personal Notes arrow_drop_up