N
N
Nikita2021-01-12 23:57:19
C++ / C#
Nikita, 2021-01-12 23:57:19

How to count the number of inversions using merge sort?

Good evening. I solved the problem and loaded it into the checking system with full confidence. As a result, the wrong answer on the 7th test.
Could you please help?
My code:

#include <iostream>
#include <fstream>
int* input_array(int* len)
{
  std::ifstream fin;
  fin.open("inversions.in");
  fin >> *len;
  int* array = new int[*len];
  for (int i = 0; i < *len; i++)
    fin >> array[i];
  fin.close();
  return array;
}

void Merge_Sort(int* array, int array_size, int* number_of_inversitions)
{
  if (array_size <= 1) return;

  int middle = array_size / 2;
  int left_size = middle;
  int right_size = array_size - middle;
  int* left = array;
  int* right = array + left_size;

  Merge_Sort(left, left_size, number_of_inversitions);
  Merge_Sort(right, right_size, number_of_inversitions);

  int left_index = 0;
  int right_index = 0;
  int index = 0; 
  int* temp_array = new int[array_size];
  while (left_index < left_size and right_index < right_size)
  {
    if (left[left_index] <= right[right_index])
      temp_array[index++] = left[left_index++];
    else {
      temp_array[index++] = right[right_index++];
      *number_of_inversitions += left_size - left_index;
    }
  }

  while (left_index < left_size)
    temp_array[index++] = left[left_index++];
  while (right_index < right_size)
    temp_array[index++] = right[right_index++];

  for (int i = 0; i < array_size; i++)
    array[i] = temp_array[i];
  delete[] temp_array;
}

int main()
{
  std::ofstream fout;
  fout.open("inversions.out");
  int number_of_inversitions = 0, n;
  int* array;
  array = input_array(&n);
  Merge_Sort(array, n, &number_of_inversitions);
  fout << number_of_inversitions;
  delete[] array;
  fout.close();
  return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-01-13
@Nikitos2002

Everything seems to be correct. What are the restrictions? There may be an overflow, because the maximum answer is n(n-1)/2. 65536 numbers in the array are enough for an int to overflow.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question