DEV Community

Cover image for Counting Inversion by piggybacking on Merge Sort with Python and C++
Abhishek Dubey
Abhishek Dubey

Posted on

1 1

Counting Inversion by piggybacking on Merge Sort with Python and C++

Solution to the problem.

  • Solution in Python
import os


def main():
 array = []
 with open("IntegerArray.txt") as file:
      array = [line.strip() for line in file]
 mergesort(array)


def merge(a,b):
    c = []
    count = 0
    while len(a) != 0 and len(b) != 0:
        if a[0] < b[0]:
            c.append(a[0])
            a.remove(a[0])
            count += 1
        else:
            c.append(b[0])
            b.remove(b[0])
            count += 1
    if len(a) == 0:
        c += b
    else:
        c += a
    # print("\n\n\n\n"+str(count)+"\n\n\n\n")
    return count


def mergesort(x):
    if len(x) == 0 or len(x) == 1:
        return x
    else:
        middle = len(x)/2
        middle = int(middle)

        a = mergesort(x[:middle])
        b = mergesort(x[middle:])
        return merge(a,b)


if __name__ == '__main__':
 main()
Enter fullscreen mode Exit fullscreen mode
  • Solution of the same problem in C++.
#include "bits/stdc++.h"
#include "iostream"
#include "fstream"
using namespace std;

long long  _mergeSort(long long arr[], long long temp[], long long left, long long right);
long long merge(long long arr[], long long temp[], long long left, long long mid, long long right);

long long mergeSort(long long arr[], long long array_size)
{
    long long *temp = (long long *)malloc(sizeof(long long)*array_size);
    return _mergeSort(arr, temp, 0, array_size - 1);
}

long long _mergeSort(long long arr[], long long temp[], long long left, long long right)
{
  long long mid, inv_count = 0;
  if (right > left)
  {
    mid = (right + left)/2;

    inv_count  = _mergeSort(arr, temp, left, mid);
    inv_count += _mergeSort(arr, temp, mid+1, right);

    inv_count += merge(arr, temp, left, mid+1, right);
  }
  return inv_count;
}


long long merge(long long arr[], long long temp[], long long left, long long mid, long long right)
{
  long long i, j, k;
  long long inv_count = 0;

  i = left;
  j = mid;
  k = left;
  while ((i <= mid - 1) && (j <= right))
  {
    if (arr[i] <= arr[j])
    {
      temp[k++] = arr[i++];
    }
    else
    {
      temp[k++] = arr[j++];
      inv_count = inv_count + (mid - i);
    }
  }


  while (i <= mid - 1)
    temp[k++] = arr[i++];

  while (j <= right)
    temp[k++] = arr[j++];

  for (i=left; i <= right; i++)
    arr[i] = temp[i];

  return inv_count;
}


int main()
{
    long long arr[100000];
    ifstream file("..PATH_TO_FILE/file.txt");
        if(file.is_open())
        {

            for(long long i = 0; i < 100000; ++i)
            {
                file >> arr[i];
             }
        }

        std::cout << mergeSort(arr, 100000);
  return 0;
}
Enter fullscreen mode Exit fullscreen mode

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post →

Top comments (1)

Collapse
 
sandordargo profile image
Sandor Dargo

You have a resource leak in the C++ implementation, you forgot to close the file.

Besides, I'd avoid adding #include "bits/stdc++.h" in any code example. It's not portable and it bloats your binary size. Include what you need and know in which header it is.

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay