Question

In: Computer Science

Fix the C++ code to count the number of inversions using the given array. The answer...

Fix the C++ code to count the number of inversions using the given array.
The answer is 8 inversions, but I am only getting 6 inversions.

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#include <iostream>
using namespace std;

int mergeInversion(int arr[], int l, int m, int r)
{
    // size of the two arrays
    int n1 = m - l + 1;
    int n2 = r - m;

    // create temporary arrays
    int L[n1];
    int R[n2];

    // Copy the data over into the temp arrays
    for(int i = 0; i < n1; ++i)
    {
        L[i] = arr[l+i];
    }
    for(int j = 0; j < n2; ++j)
    {
        R[j] = arr[m + 1 + j];
    }

    // Counting the inversions.
    int counter = 0;
    for(int i = 0; i < n1; i++)
    {
        for(int j = 0; j < n2; j++)
        {
            if(L[i] > R[i]) // check if its an inversion
            {
                counter++;
            }
        }
    }
    return counter;
}

// Divide-and-Conquer for inversions
int countInversions(int arr[], int l, int r)
{
    int countIs = 0;

    if(l < r)
    {
        // find middle pt
        int m = (l+r)/2;

        // sort the first half and last half
        countIs = countIs + countInversions(arr, l, m);     // first half sub-array doing inversion recursively
        countIs = countIs + countInversions(arr, m+1, r);   // last half sub-array doing inversion recursively

        // now conquer by merging the sub-arrays!
        countIs = countIs + mergeInversion(arr, l, m, r);   // count the inversions in both arrays
    }
    return countIs;
}

// driver
int main()
{
    // part(c) using the input a = [2, 6, 1, 5, 4, 3]
    int a[] = {2, 6, 1, 5, 4, 3};

    // array size
    int n = sizeof(a)/sizeof(*a);


    cout << "\nTotal # of Inversions: " << countInversions(a, 0, n-1);

    return 0;
}

Solutions

Expert Solution

#include <bits/stdc++.h>
using namespace std;

int mergeInversion(int arr[], int l, int m, int r)
{
// size of the two arrays
int n1 = m - l + 1;
int n2 = r - m;

// create temporary arrays
int L[n1];
int R[n2];

// Copy the data over into the temp arrays
for(int i = 0; i < n1; ++i)
{
L[i] = arr[l+i];
}
for(int j = 0; j < n2; ++j)
{
R[j] = arr[m + 1 + j];
}
int i=0,j=0,k=l,count=0;
// i and j are index of left and right arrays during merging
//during merging if L[i] is greater than R[j], then there are (n1 – i) inversions. because left and right subarrays are sorted,
//so all the remaining elements in left-subarray (L[i+1], L[i+2] … L[mid]) will be greater than R[j]
  
while(i<n1 && j<n2){
if(L[i]<=R[j])
arr[k++] = L[i++];
else{
arr[k++] = R[j++];
count += n1-i;
}
}
while(i<n1)
arr[k++] = L[i++];
while(j<n2)
arr[k++] = R[j++];
return count;
  


}

// Divide-and-Conquer for inversions
int countInversions(int arr[], int l, int r)
{
int countIs = 0;

if(l < r)
{
// find middle pt
int m = (l+r)/2;

// sort the first half and last half
countIs = countIs + countInversions(arr, l, m); // first half sub-array doing inversion recursively
countIs = countIs + countInversions(arr, m+1, r); // last half sub-array doing inversion recursively

// now conquer by merging the sub-arrays!
countIs = countIs + mergeInversion(arr, l, m, r); // count the inversions in both arrays
}
return countIs;
}

// driver
int main()
{
// part(c) using the input a = [2, 6, 1, 5, 4, 3]
int a[] = {2, 4, 1, 3, 5};

// array size
int n = sizeof(a)/sizeof(*a);


cout << "\nTotal # of Inversions: " << countInversions(a, 0, n-1);

return 0;
}


Related Solutions

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;...
I am running this code using C to count the words in char array, but somehow...
I am running this code using C to count the words in char array, but somehow it keeps counting the total characters + 1. Any solution to fix this problem? #include <stdio.h> int main() {    char input[1001];    int count =0;    fgets(input, 1001, stdin);    char *array = input;    while(*array != '\0')       {        if(*array == ' '){            array++;        }        else{        count++;        array++;...
write code to count the number of odd integers in an array of 100 random integers...
write code to count the number of odd integers in an array of 100 random integers in the range [0,99].
Can anyone fix this code? The code isn't rounding the answer to the nearest whole number...
Can anyone fix this code? The code isn't rounding the answer to the nearest whole number like 2.345 should be 2 and 2.546 should be 3 but the round() function isn't working as expected. The round() function is rounding 2.546 to 2 which is incorrect since 4 and below should be rounded to 2 and 5 and above should be rounded to 3. Here is the code: #importing xlwt library to write into xls import xlwt from xlwt import Workbook...
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). Give a brute-force algorithm with running time of O(n^2). Using the technique of divide-and-conquer, design an algorithm with running time of O(nlog n).
I. Answer part A,B, C and D. 1a) Count the number of times a given char...
I. Answer part A,B, C and D. 1a) Count the number of times a given char occurs in a given range of a String parameter (i.e. starting at a given start index, and up to but not including and end index). If end is greater than the length of the String, then the method should stop looking at the end of the String. countCharsInRange("java", "v", 1, 2) → 0 countCharsInRange("java", "v", 0, 2) → 0 countCharsInRange("java", "v", 0, 3) →...
Write a code using c# Maximum Sub Array.
Write a code using c# Maximum Sub Array.
(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.
As code is given below, follow the instructions: 1. Count the number of comparisons and find...
As code is given below, follow the instructions: 1. Count the number of comparisons and find where to put that counter in the code 2. Pick a random pivot, right pivot, left pivot, middle pivot for each smaller array /sub-array import java.util.*; import java.util.List; public class QuickSort { public static void main(String[] args) { int[] values = { 6, 5, 4, 3, 1, 7, 8 }; System.out.println("Original order: "); for (int element : values) System.out.print(element + " "); IntQuickSorter.quickSort(values); System.out.println("\nFirst...
Write a code in c++ using dynamic array of structure and dynamic array list. Make a...
Write a code in c++ using dynamic array of structure and dynamic array list. Make a dummy list for a company which stores following information about its customers. Customer ID Customer Name Gender Total items purchased Item category 20% discount in percentage of total purchase amount. Use dynamic array to save at least 20 items by dividing them into 3 different categories. Make a dummy list of items that company sells by dividing them into two categorizes. Items has following...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT