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

(Programming: Counting threshold inversions) You’ll be given an array (of integers) and a threshold value as...
(Programming: Counting threshold inversions) You’ll be given an array (of integers) and a threshold value as input, write a program to return the number of threshold inversions in the array. An inversion between indices i < j is a threshold inversion if ai > t ∗ aj , where t is the threshold value given as input.
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...
Please do Part III Part I Problem statement: Given an array of 'n' non-duplicate integers, find...
Please do Part III Part I Problem statement: Given an array of 'n' non-duplicate integers, find pairs of integers from the array that make the sum equal to K. Eg. [1, 2, 7, 11, 6, 9, 5] K= 12 Soln: (1,11), (7,5). Part II Write an Oracle for testing this program using Data Flow Testing. As usual, write down test cases in a tabular form with reasons, inputs, expected output etc. Part III   1.       Identify the basic blocks in your...
We are given an array of n numbers A in an arbitrary order. Design an algorithm...
We are given an array of n numbers A in an arbitrary order. Design an algorithm to find the largest and second largest number in A using at most 3/2n -2 comparisons. (i) describe the idea behind your algorithm in English (3 points); (ii) provide pseudocode (5 points); (iii) analyze the number of comparisons used in your algorithm (2 points).
Array with Pointers Find Continuous Sub-Array C++ Problem: Given an unsorted array A of size N...
Array with Pointers Find Continuous Sub-Array C++ Problem: Given an unsorted array A of size N of non-negative integers, find a continuous sub-array which adds to the given number. Declare dynamic arrays and use only pointers syntax (no [ ]’s or (ptr+i) stuff.     Input will be the number of input values to enter followed by the sum to compare with. Print out the continuous sub-array of values that are equal to sum or the message ‘No sum found’. There...
Let iqsort(A, 1, n) be an algorithm that sorts an array A with n integers. It...
Let iqsort(A, 1, n) be an algorithm that sorts an array A with n integers. It works as follows: iqsort(A, p, q){ if p ≥ q, return; r=partition(A, p, q); //run quick sort on the low part quicksort(A, p, r − 1); //run insert sort on the high part insertsort(A, r + 1, q); } Compute the best-case, worst-case, and average-case complexities of iqsort.
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
write a recursive algorithm to find the maximum element in an array of n elements and...
write a recursive algorithm to find the maximum element in an array of n elements and analyze its time efficiency. (I am using c++ programming language)
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT