Q:

Write a JavaScript program to find the number of inversions of a given array of integers

0

Write a JavaScript program to find the number of inversions of a given array of integers. 
Note: Two elements of the array a stored at positions i and j form an inversion if a[i] > a[j] and i < j.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

function number_of_InversionsNaive(arr) {
    var ctr = 0;
    for (var i = 0; i < arr.length; i++) {
        for (var j = i + 1; j < arr.length; j++) {
            if (arr[i] > arr[j]) 
              ctr++;
        }
    }
    return ctr;
}

console.log(number_of_InversionsNaive([0, 3, 2, 5, 9]));   
console.log(number_of_InversionsNaive([1, 5, 4, 3]));   
console.log(number_of_InversionsNaive([10, 30, 20, -10]));  

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now