w3resource

JavaScript: Find the number of inversions of a specified array of integers

JavaScript Basic: Exercise-102 with Solution

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.

Sample Solution:

JavaScript Code:

// Function to count the number of inversions in an array (naive approach)
function number_of_InversionsNaive(arr) {
    var ctr = 0; // Counter for inversions

    // Loop through the array elements
    for (var i = 0; i < arr.length; i++) {
        for (var j = i + 1; j < arr.length; j++) {
            // If an inversion is found, increment the counter
            if (arr[i] > arr[j]) 
              ctr++;
        }
    }

    return ctr; // Return the count of inversions
}

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

Sample Output:

1
3
4

Live Demo:

See the Pen javascript-basic-exercise-102 by w3resource (@w3resource) on CodePen.


Flowchart:

Flowchart: JavaScript - Find the number of inversions of a specified array of integers

ES6 Version:

// Function to count inversions in an array
const number_of_InversionsNaive = (arr) => {
    let ctr = 0; // Counter to track inversions

    // Loop through the array to count inversions
    for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
            // Increment the counter if an inversion is found
            if (arr[i] > arr[j]) {
                ctr++;
            }
        }
    }

    return ctr; // Return the total count of inversions
}

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

Previous: JavaScript program to check whether a given string contains only Latin letters and no two uppercase and no two lowercase letters are in adjacent positions.
Next: JavaScript program to find the maximum number from a given positive integer by deleting exactly one digit of the given number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.