简体   繁体   中英

Inversions in Array

I am trying to count the number of inversions in this array and I am really not sure where to start the count. I have tried many different spots and I thought this would be the right place to increment the counter, but I am mistaken because the output is way off. Any tips on how to understand where to put the increment? I think I'm just confused because of the recursive part. I can't wrap my head around it. Ugh. Thanks so much in advance.

#include <iostream>
using namespace std;

int count = 0;
void merge(int[], int, int, int);

void mergesort(int array[], int low, int high)
{
int mid;

if(low < high)
{
   mid = low + (high-low)/2;
   mergesort(array, low, mid);
   mergesort(array, mid+1, high);

   merge(array, low, mid, high);
}
}

void merge(int array[], int low, int mid, int high)
{
   int h, i, j, b[high + 1], k;
   h = low;
   i = low;
   j = mid + 1;

while((h <= mid) && (j <= high))
{

   if(array[h] <= array[j])
   {
      b[i] = array[h];
      h++;


   }
   else
   {
      b[i] = array[j];
      j++;
      count++;

   }
   i++;
}
if( h > mid)
{   
   for(k = j; k <= high; k++)
   {
      b[i] = array[k];
      i++;    

   }

}
   else
   {
      for(k = h; k <= mid; k++)
      {
         b[i] = array[k];
         i++;

      }


   }
  for( k = low; k <= high; k++)
   {
     array[k] = b[k];

   }  

}

int main()
{

   int size;
   cin >> size;
   int data[size];
   for(int i = 0; i < size; i++)
   {
      cin >> data[i] ;
   }
mergesort(data, 0, size-1);
   for(int i = 0; i < size; i++)
   {
       cout << data[i];
   }
   cout << endl << count;
}

What's the number of inversions in the array a? It equals the number of inversions in first half of the array a(X) plus number of inversions in the second half of the array a (Y) and number of inversions where one element is in the first half and another is in the second(Z) So total number of inversions = X+Y+Z where X will be the result of mergesort of the first half,Y mergesort of the second half and Z will be the result of the merge.

X = mergesort(firstHalf of a)
Y = mergesort(secondHalf of a)
Z = merge(firstHalf,secondHalf) 

I made some changes to your code and now it works, I will give some hints: change types of mergesort and merge to long(or int)

if(low < high)
{
    mid = low + (high-low)/2;
    long x =mergesort(array, low, mid);
    long y =mergesort(array, mid+1, high);

    long z =merge(array, low, mid, high);
    return x+y+z;
}
else
    return 0;

I also changed mergesort to this. Your merge is mostly okay but you shouldn't increase count by one but by number mid-h+1 . I am not quite sure that I should provide all the code

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