I have an Array, lets say {7,6,4,2}
.
I need an efficient algorithm to find number of times n
smaller numbers occur after a given element, where each element is smaller than the preceding one.
For example: for n=3
, a[i]>a[j]>a[k]
and i < j < k
. Here the output should be {7,6,4}
,{7,6,2}
and {6,4,2}
.
I have a simple algorithm with 3 for loops but obviously a solution with O(n^3)
complexity is not feasible.
Here is the sample code I created for n=3
.
// Array is initialized and given values. Size of Array is n1
for(int i=0;i<n1-2;i++)
{
for(int j=i+1;j<n1-1;j++)
{
if(a[j]<a[i])
{
for(int k=j+1;k<n1;k++)
{
if(a[k]<a[j])
{
cnt++;
}
}
}
}
}
Could you please link me to an algorithm I could use or provide me with algorithm below. JAVA preferred.