PHP Program to Count Inversions of size three in a given array
Last Updated :
23 Jul, 2024
Given an array arr[] of size n. Three elements arr[i], arr[j] and arr[k] form an inversion of size 3 if a[i] > a[j] >a[k] and i < j < k. Find total number of inversions of size 3.
Example :
Input: {8, 4, 2, 1}
Output: 4
The four inversions are (8,4,2), (8,4,1), (4,2,1) and (8,2,1).
Input: {9, 6, 4, 5, 8}
Output: 2
The two inversions are {9, 6, 4} and {9, 6, 5}
Simple approach
Loop for all possible value of i, j and k and check for the condition a[i] > a[j] > a[k] and i < j < k.
PHP
<?php
// A O(n^2) PHP program to
// count inversions of size 3
// Returns count of
// inversions of size 3
function getInvCount($arr, $n)
{
// Initialize result
$invcount = 0;
for ($i = 1; $i < $n - 1; $i++)
{
// Count all smaller elements
// on right of arr[i]
$small = 0;
for($j = $i + 1; $j < $n; $j++)
if ($arr[$i] > $arr[$j])
$small++;
// Count all greater elements
// on left of arr[i]
$great = 0;
for($j = $i - 1; $j >= 0; $j--)
if ($arr[$i] < $arr[$j])
$great++;
// Update inversion count by
// adding all inversions
// that have arr[i] as
// middle of three elements
$invcount += $great * $small;
}
return $invcount;
}
// Driver Code
$arr = array(8, 4, 2, 1);
$n = sizeof($arr);
echo "Inversion Count : "
, getInvCount($arr, $n);
// This code is contributed m_kit
?>
OutputInversion Count : 4
Complexity Analysis:
- Time complexity of this approach is : O(n^3)
- Auxiliary Space: O(1)
As constant extra space is used.
Better Approach
We can reduce the complexity if we consider every element arr[i] as middle element of inversion, find all the numbers greater than a[i] whose index is less than i, find all the numbers which are smaller than a[i] and index is more than i. We multiply the number of elements greater than a[i] to the number of elements smaller than a[i] and add it to the result.
Below is the implementation of the idea.
PHP
<?php
// A O(n^2) PHP program to count
// inversions of size 3
// Returns count of
// inversions of size 3
function getInvCount($arr, $n)
{
// Initialize result
$invcount = 0;
for ($i = 1; $i < $n - 1; $i++)
{
// Count all smaller elements
// on right of arr[i]
$small = 0;
for ($j = $i + 1; $j < $n; $j++)
if ($arr[$i] > $arr[$j])
$small++;
// Count all greater elements
// on left of arr[i]
$great = 0;
for ($j = $i - 1; $j >= 0; $j--)
if ($arr[$i] < $arr[$j])
$great++;
// Update inversion count by
// adding all inversions that
// have arr[i] as middle of
// three elements
$invcount += $great * $small;
}
return $invcount;
}
// Driver Code
$arr = array (8, 4, 2, 1);
$n = sizeof($arr);
echo "Inversion Count : " ,
getInvCount($arr, $n);
// This code is contributed by m_kit
?>
OutputInversion Count : 4
Complexity Analysis:
- Time Complexity of this approach : O(n^2)
- Auxiliary Space: O(1)
As constant extra space is used.
Binary Indexed Tree Approach :
Like inversions of size 2, we can use Binary indexed tree to find inversions of size 3. It is strongly recommended to refer below article first.
count inversions of size two Using BIT
The idea is similar to above method. We count the number of greater elements and smaller elements for all the elements and then multiply greater[] to smaller[] and add it to the result.
Solution :
- To find out the number of smaller elements for an index we iterate from n-1 to 0. For every element a[i] we calculate the getSum() function for (a[i]-1) which gives the number of elements till a[i]-1.
- To find out the number of greater elements for an index we iterate from 0 to n-1. For every element a[i] we calculate the sum of numbers till a[i] (sum smaller or equal to a[i]) by getSum() and subtract it from i (as i is the total number of element till that point) so that we can get number of elements greater than a[i].
Please refer complete article on Count Inversions of size three in a given array for more details!
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
13 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. How do
14 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high. We sort the array using multiple passes. After the fi
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Conditions to apply Binary Search Algorithm in a Data S
15+ min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted. First we find the smallest element a
8 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1. Note: The given graph does not contain any negative edge. Exampl
12 min read