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

// countlnv.cpp file

#include <iostream>
#include <vector>

using namespace std;

int numinv;

void mergeSort(vector<int>& numvec, int left, int right);
int merge(vector<int>& numvec , int left, int mid, int right);

int countInv(vector<int>& numvec) {
numinv = 0;
mergeSort(numvec, 0, numvec.size());
cout << "Sorted output: ";
for (auto ele : numvec)
   cout << ele << " ";
   cout << endl;
return numinv;
  
}

//Sorts the input vector and returns the number of inversions in that vector
void mergeSort(vector<int>& numvec, int left, int right){
// Your code here

}

int merge(vector<int>& numvec , int left, int mid, int right){
// Your code here


}

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Use the following test code to evaluate your implementation

// countlnv_test.cpp

/* 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
}

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Thank you for your time and help!

Solutions

Expert Solution

#include <iostream>
#include <vector>

using namespace std;

int numinv;

void mergeSort(vector<int>& numvec, int left, int right);
int merge(vector<int>& numvec , int left, int mid, int right);

int countInv(vector<int>& numvec) {
        numinv = 0;
        mergeSort(numvec, 0, numvec.size());
        cout << "Sorted output: ";
        for (auto ele : numvec)
                cout << ele << " ";
        cout << endl;
        return numinv;
}

//Sorts the input vector and returns the number of inversions in that vector
void mergeSort(vector<int>& numvec, int left, int right){
        // no need to sort a single element.
        if(left + 1 < right) {
                int mid = (left + right) / 2;
                mergeSort(numvec, left, mid);
                mergeSort(numvec, mid, right);
                numinv += merge(numvec, left, mid, right);
        }
}

// mid is start of next array.
// right is excluded.
int merge(vector<int>& numvec , int left, int mid, int right){
        
    // Copy the vector to tmeporary vector, so that we can 
    // make the changes to the original
    vector<int> temp = numvec; 
 
    int inversionCount = 0; 
  
    int i = left;
    int j = mid;
    int k = left;
    while ((i <= mid - 1) && (j < right)) { 
        if (temp[i] <= temp[j]) { 
            numvec[k++] = temp[i++]; 
        } 
        else { 
            numvec[k++] = temp[j++];
            inversionCount += (mid - i);  // at this point, remaining elements are inverted
        }
    }
    
    // copy remaining elements from any half back to original array
    while (i <= mid - 1) {
        numvec[k++] = temp[i++]; 
    }
  
    while (j < right) {
        numvec[k++] = temp[j++]; 
    }
  
  
    return inversionCount;
}


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
}
**************************************************

Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.

Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.


Related Solutions

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...
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...
sorting- Inversion Count for an array indicates Language: c++ Your solution has to be O(n log...
sorting- Inversion Count for an array indicates Language: c++ Your solution has to be O(n log n). please write comments *countinv.cpp* // Count inversions - homework // Based off of mergesort #include <vector> #include <algorithm> // For copy 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 } //test code /* Count the...
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...
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)...
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].
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT