简体   繁体   中英

Implement Count inversion using merge sort algorithm in c++

I need to implement the count inversion algorithm for a homework but i couldn't figure out what is the problem in my code.Our professor asked us to implement count inversion in c++(Which i didn't work with it much) without using any C++ libraries only i could include <iostream> and use std only for output ( cout<< ) and that's it, also he gave us this piece here :

 void count_inversion(int a[],int n){
    count_inversion(a, n / 2);
    count_inversion(a + (n / 2), n / 2);
    count_inversion_merge(a, n / 2, n);
  }

and said we should implement the count_inversion_merge function and use this piece as a hint. So i tried to adapt the code a little to work but still have no luck.

Here is my code :

 int count_inversion_merge(int array[], int mid, int n) {
        for (k = 0; k < n; k++) {
            if (j == n || (i < mid && array[i] < array[j])) {
                b[k] = array[i];
                i++;
            } else {
                b[k] = array[j];
                j++;
                inversion++;
            }
        }

    }

My First input int a[] ={ 2, 4, 1, 3, 5 }; should return 3 but it returns 5 and my second output should be 5 and i get 5. I hope that someone could point out where is my error.

Your basic idea is right, but there 2 problems in your code. One is conceptual, another is in code.

  1. In the else block of merge step, you are increasing the inversion by one. Instead, you should increase it by how many values you have in the left part. So in else block you should use, inversion += mid-i; instead of inversion++; Because, you need to actually count the number of swaps required. At this point, for the value of array[j] , you have mid - i (rest of left array) number of elements which were actually needed to swap corresponding to array[j] . That means, if you would use bubble sort, you would need to swap all the rest elements in left array ( mid-i ) with this single value ( array[j] ). So, for this array[j] you should increase number of elements rest in the left sub-array.

  2. In the recursive calling of count_inversion , you are missing some values in every call. eg lets say n=5 . Then you are using 5/2 = 2 at left and 5/2 = 2 at right. But you are missing the last element at the right side. You can solve it by using as following in your second recursive call. Here, you should use the rest of the length you used from first call.

    count_inversion(a + (n / 2), n - n / 2);

A little modified code from yours with fixes: https://ideone.com/raKD7T

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM