Question

In: Computer Science

please write in c++ Algorithm Design problem: Counting inversions: given an array of n integers, find...

please write in c++

Algorithm Design problem:

Counting inversions: given an array of n integers, find out the total number of inversions in the given sequence. For example, for the sequence of 2, 4, 1, 3, 5, there are three inversions (2,1), (4,1), and (4,3).

  1. Give a brute-force algorithm with running time of O(n^2).
  2. Using the technique of divide-and-conquer, design an algorithm with running time of O(nlog n).

Solutions

Expert Solution

Program: In this program, we write two functions to count the inversions in an array. The first function runs in a time complexity of O(n^2) and the second function runs in O(nlogn) time complexity.

Function 1 algorithm:

  • Traverse the array from start to end
  • Create another for loop and for every element find the count of elements smaller than the current element
  • Keep updating the count while checking for each element
  • Return the count of inversions.

Function 2 algorithm:

  • The idea is based on merge sort, divide the array into two halves in each step until the base case is reached which is when there is only one element in the given half.
  • Create a function mergeSort to divide the array into two halves and find the answer by summing the number of inversions in the first half, number of inversion in the second half and the number of inversions by merging the two.
  • Create a function merge that counts the number of inversions when two halves of the array are merged, create indices i and j to keep track of the first(left) half and second(right) half of array. If a[i] is greater than a[j], then there are (mid – i) inversions. since left and right subarrays are sorted, as a result all the remaining elements in left-subarray (a[i+1], a[i+2] … a[mid]) will be greater than a[j].
  • Return the inversion count

Code:

#include <iostream>
using namespace std;

// Method 1: Time complexity O(n^2)
int inversionCount1(int arr[], int n){

    int invCount = 0;
    // Traverse through the array till the end

    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {

            // count the number of elements smaller than current element
            // update count
            if (arr[i] > arr[j]) {
                invCount++;
            }
        }
    }

    // Return count
    return invCount;
}


// Method 2: Time Complexity O(nlogn)
// Using merge sort

// Function merge
int merge(int arr[], int temp[], int left, int mid, int right){

    // Create indices for left and right array i.e i ad j
    int i = left, j = mid, k = left;

    // Initialize inversion count
    int invCount = 0;

    // Run a loop while loop until i and j are in range
    while ((i <= mid - 1) && (j <= right)) {

        // If left array element is small than assign that in the array
        if (arr[i] <= arr[j]) {
            temp[k++] = arr[i++];
        }
        else {
            temp[k++] = arr[j++];

            // Else update inversion count
            invCount = invCount + (mid - i);
        }
    }

    // Check if any element is present in left side array
    while (i <= mid - 1) {
        temp[k++] = arr[i++];
    }

    // Check if any element is present in right side array
    while (j <= right) {
        temp[k++] = arr[j++];
    }

    // Store the values in temp
    for (i = left; i <= right; i++) {
        arr[i] = temp[i];
    }

    return invCount;
}

int mergeSort(int arr[], int temp[], int left, int right){

    // Initialise inversion count
    int mid, invCount = 0;

    // Check if left is less than right
    if (right > left) {

        // Calculate mid
        mid = (right + left) / 2;

        // Update count
        invCount += mergeSort(arr, temp, left, mid);
        invCount += mergeSort(arr, temp, mid + 1, right);
        invCount += merge(arr, temp, left, mid + 1, right);
    }

    // Return count
    return invCount;
}


// Inversion count2 : using merge Sort
int inversionCount2(int arr[], int array_size){

    // Create temporary array
    int temp[array_size];

    // Call mergesort
    return mergeSort(arr, temp, 0, array_size - 1);
}

int main(){

    int arr[] = {2, 4, 1, 3, 5};
    int n = sizeof(arr) / sizeof(arr[0]);
    int ans1 = inversionCount1(arr, n);
    int ans2 = inversionCount2(arr, n);

    cout << ans1 << endl;
    cout << ans2 << endl;
    return 0;
}

Output:



Related Solutions

Write a C++ program to find the number of pairs of integers in a given array...
Write a C++ program to find the number of pairs of integers in a given array of integers whose sum is equal to a specified number.
Write a C++ program to find K largest elements in a given array of integers. For...
Write a C++ program to find K largest elements in a given array of integers. For eeample, if K is 3, then your program should ouput the largest 3 numbers in teh array. Your program is not supposed to use any additional array.
Let A be an array of non-decreasing N integers. Write an algorithm that returns the number...
Let A be an array of non-decreasing N integers. Write an algorithm that returns the number of pairs of integers in A that are equal. Analyze your algorithm thoroughly. Your analysis should include a thorough examination of both the best and the worst-case scenarios. This includes a description of what the best and worst cases would look like. You should include both space and time in your analysis, but keep in mind that space refers to “extra space,” meaning in...
Given a minimum unimodal array of integers, run the binary search algorithm to find the minimum...
Given a minimum unimodal array of integers, run the binary search algorithm to find the minimum element. You need to show the initial and the iteration-level values of the left index, right index and middle index as well as your decisions to reduce the search space in each iteration. 42 39 2 6 9 16 20 28 31 34
Use C Programming - Given an array of integers and a number K, find the smallest...
Use C Programming - Given an array of integers and a number K, find the smallest element in array greater than or equal to K. If such element exists in the array, display it otherwise display "-1". Example: Input:     8     1 3 4 7 8 9 9 10     5     where: First line represents the number of elements in the array. Second line represents the elements in the array. Third line represents the value of K. Output:     7 Explanation:...
Given an array of positive integers except one negative integer. Develop a divide-conquer algorithm to find...
Given an array of positive integers except one negative integer. Develop a divide-conquer algorithm to find the index of the negative integer, and compute its average complexity.
c++ is the language Code an O(nlog(n)) algorithm to count the number of inversions DO NOT...
c++ is the language Code an O(nlog(n)) algorithm to count the number of inversions DO NOT ADD OR EDIT FUNCTIONS USE THESE ONLY DO NOT EDIT THE TEST FILE EITHER countInv.cpp #include <vector> #include <algorithm> using namespace std; int mergeInv(vector<int>& nums, vector<int>& left, vector<int>& right) { // You will need this helper function that calculates the inversion while merging // Your code here } int countInv(vector<int>&nums) { // Your code here } countInv_test.cpp #include <iostream> #include <vector> using namespace std;...
Problem Definition: Problem: Given an array of integers print all pairs of integers a and b...
Problem Definition: Problem: Given an array of integers print all pairs of integers a and b where a + b is equal to a given number. For example, consider the following array and suppose we want to find all pairs of integers a and b where a + b = 16 A= [ 10, 4, 6, 15, 3, 5, 1, 13] The following are pairs that sum to 16: 13, 3 6, 10 15, 1 Your program should print these...
1. Given an array of integers a dimension n. If the array contains the same number...
1. Given an array of integers a dimension n. If the array contains the same number of even and odd elements get (a1 + an) (a2 + an-1) ... 2. Given an array of integers dimension n. All array elements with even numbers preceding the first element to the maximum, multiplied by the maximum. 3. Given an array of dimension n. Insert after each zero element of the element in the middle (or the amount of secondary elements for even...
c++ please Write and testa C++ main program that: declare an array arrof 6 integers Prompt...
c++ please Write and testa C++ main program that: declare an array arrof 6 integers Prompt the user for 6 integer values and store them in arr. Prompt the user for a target integer target. Search for targetin arr. If targetis found to match an element in the arr, then the program prints out a message which contains the address of the found element, otherwise, if no element found then the message “the element target not found” will be printed...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT