Question

In: Computer Science

Inversion Count for an array indicates – how far (or close) the array is from being...

Inversion Count for an array indicates – how far (or close) the array is from being sorted. If array is already sorted then inversion count is 0. If array is sorted in reverse order that inversion count is maximum. Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j

Example: The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3).

What would the complexity of a brute force approach be?

Code an O(nlog(n)) algorithm to count the number of inversions. Hint - piggy back on the merging step of the mergesort algorithm.

Complete the code in the functions indicated to count inversions.

countInv.cpp ====== code: (EDIT ONLY THIS FILE)

/ Count inversions - homework

// Based off of mergesort

#include

#include // For copy

using namespace std;

int mergeInv(vector& nums, vector& left, vector& right) {

// You will need this helper function that calculates the inversion while merging

// Your code here

}

int countInv(vector&nums) {

// Your code here

} // END OF COUNTINV.CPP FILE

countInv_test.cpp ===== code: (DO NOT EDIT THIS FILE)

/* Count the number of inversions in O(n log n) time */

#include <iostream>

#include <vector>

using namespace std;

int countInv(vector<int>& numvec);

int main()

{

int n;

vector<int> numvec{4, 5, 6, 1, 2, 3};

n = countInv(numvec);

cout << "Number of inversions " << n << endl; // Should be 9

   numvec = {1, 2, 3, 4, 5, 6};

n = countInv(numvec);

cout << "Number of inversions " << n << endl; // Should be 0

   numvec = {6, 5, 4, 3, 2, 1};

n = countInv(numvec);

cout << "Number of inversions " << n << endl; // Should be 15  

numvec = {0, 0, 0, 0, 0, 0};

n = countInv(numvec);

cout << "Number of inversions " << n << endl;; // Should be 0

} / END OF COUNTINV_TEST.CPP FILE

Code an O(nlog(n)) algorithm to count the number of inversions. Hint - piggy back on the merging step of the mergesort algorithm.

Keep the COUNTINV_TEST.CPP file seperate from the COUNTINV.CPP file when coding.

Thank you so much for your help.

Solutions

Expert Solution

NOTE: the code written is tested via below input correctly , use indentation and copy fully to working code

trick is using merge sort merging step we have (mid-i) inversion while merging two arrays.

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

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

int merge(vector<int>& nums, int left, int mid, int right) {
   int i, j, k, n;
   int inv_count = 0;
   i = left, j = mid, k = left, n = nums.size();
   vector<int> temp(n);
   while ((i <= mid - 1) && (j <= right)) {
       if (nums[i] <= nums[j])
           temp[k++] = nums[i++];
       else {
           temp[k++] = nums[j++];
           // this is mid-1 inversions
           inv_count = inv_count + (mid - i);
       }
   }

   while (i <= mid - 1)
       temp[k++] = nums[i++];
   while (j <= right)
       temp[k++] = nums[j++];

   // assigned temp to nums vector
   for (i = left; i <= right; i++) {
       nums[i] = temp[i];
   }

   return inv_count;
}

int mergeInv(vector<int>& nums, int left, int right) {

// You will need this helper function that calculates the inversion while merging

// Your code here
   int mid, inv_count = 0;
   if (right > left) {
       mid = (right + left) / 2;
       inv_count += mergeInv(nums, left, mid);
       inv_count += mergeInv(nums, mid + 1, right);

       //merge two parts by calling helper method
       inv_count += merge(nums, left, mid + 1, right);
   }
   return inv_count;

}

int countInv(vector<int>& nums) {

// Your code here

   return mergeInv(nums, 0, nums.size() - 1);

}


int main(int argc, char const *argv[])
{
   vector<int> v = {4, 5, 6, 1, 2, 3};
   cout << countInv(v) << '\n';
   return 0;
}

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

OUTPUT:


Related Solutions

Description Inversion Count for an array indicates – how far (or close) the array is from...
Description Inversion Count for an array indicates – how far (or close) the array is from being sorted. If array is already sorted then inversion count is 0. If array is sorted in reverse order that inversion count is the maximum. Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j . Example: The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3). Requirements: • Design...
Let "fit" summarize how far the in-sample observations are from the fitted model; e.g., fit=100 indicates...
Let "fit" summarize how far the in-sample observations are from the fitted model; e.g., fit=100 indicates worse fit than fit=50. Let "penalty" be increasing in the size of a model, specifically the number of parameters in the model, given the same sample size; e.g., given sample size 80, penalty is larger for a model with 10 parameters than for a model with 5 parameters. To prevent overfitting when choosing a forecasting model, you could maximize (fit + penalty) minimize (fit...
Is New Zealand far or close from a steady state economy and what is their depreciation...
Is New Zealand far or close from a steady state economy and what is their depreciation rate?
Based on the source code below, add codes to count how many times array has been...
Based on the source code below, add codes to count how many times array has been access by this program in sorting the array using the insertion sort. Explain how did you count the number of array access on this code. Note that this program tests on 100 until 5000 integers, with increment of 100. import random #create randomized array of length 'length' from range 0 up to max def create_array(length=100, max=5000): return [random.randint(0,max) for _ in range(length)] #executes insertion...
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].
how are the distributions of gains from trade changing as far as labor and capital are...
how are the distributions of gains from trade changing as far as labor and capital are concerned? can we still use the h-0 model? The topic is about globalization inequality. Please type the answer. Thanks
Write a line of code that indicates to the compiler that the method being declared overrides...
Write a line of code that indicates to the compiler that the method being declared overrides a superclass method. Write a line of code that specifies that class Fly inherits from class Insect. Call superclass Insect's toString method from subclass Fly's tostring method. Call superclass Insect's constructor from subclass Fly's constructor, assume that the constructor receives an integer for number of legs and a string for the ability it has.
Country Ferrara is an economy in the far west. You are being summoned by the King...
Country Ferrara is an economy in the far west. You are being summoned by the King of Ferrara to help his ministers to estimate the GDP of Ferrara in 2017. Please use the formulas and techniques to estimate the GDP using any two methods. Name the methods and show the GDP estimation. Please see the table below Interest Payments 170 Consumption 500 Wages and Salaries 250 Depreciation costs 50 Exports 120 Rental income 320 Net Indirect taxes ( taxes- subsidies)...
How does arbitration differ from mediation? (200 word count)
How does arbitration differ from mediation? (200 word count)
A 3.36 µC charge is 1.17 cm from a 5.67 µC charge. How far from the...
A 3.36 µC charge is 1.17 cm from a 5.67 µC charge. How far from the larger charge will the electric field be zero? Answer in cm.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT