Skip to main content

Counting Inversion: Piggybacking on Merge Sort with Python and C++


This is a solution to Coursera's algorithm problem

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()
Implementation of the same problem in C++ is as following.

#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);

/* This function sorts the input array and returns the
   number of inversions in the array */
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);
}

/* An auxiliary recursive function that sorts the input array and
  returns the number of inversions in the array. */
long long _mergeSort(long long arr[], long long temp[], long long left, long long right)
{
  long long mid, inv_count = 0;
  if (right > left)
  {
    /* Divide the array long longo two parts and call _mergeSortAndCountInv()
       for each of the parts */
    mid = (right + left)/2;

    /* Inversion count will be sum of inversions in left-part, right-part
      and number of inversions in merging */
    inv_count  = _mergeSort(arr, temp, left, mid);
    inv_count += _mergeSort(arr, temp, mid+1, right);

    /*Merge the two parts*/
    inv_count += merge(arr, temp, left, mid+1, right);
  }
  return inv_count;
}

/* This funt merges two sorted arrays and returns inversion count in
   the arrays.*/
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; /* i is index for left subarray*/
  j = mid;  /* j is index for right subarray*/
  k = left; /* k is index for resultant merged subarray*/
  while ((i <= mid - 1) && (j <= right))
  {
    if (arr[i] <= arr[j])
    {
      temp[k++] = arr[i++];
    }
    else
    {
      temp[k++] = arr[j++];

     /*this is tricky -- see above explanation/diagram for merge()*/
      inv_count = inv_count + (mid - i);
    }
  }

  /* Copy the remaining elements of left subarray
   (if there are any) to temp*/
  while (i <= mid - 1)
    temp[k++] = arr[i++];

  /* Copy the remaining elements of right subarray
   (if there are any) to temp*/
  while (j <= right)
    temp[k++] = arr[j++];

  /*Copy back the merged elements to original array*/
  for (i=left; i <= right; i++)
    arr[i] = temp[i];

  return inv_count;
}

/* Driver program to test above functions */
int main()
{
    long long arr[100000];
    ifstream file("/home/dubey/_Code/Merge/file.txt");
        if(file.is_open())
        {

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

        std::cout << mergeSort(arr, 100000);
  return 0;
}

Comments

Popular posts from this blog

Heckerrank Problem: Birthday Cake Candles

This is a solution to Hackerrank's algorithm problem

Implementation of the same problem in C++ is as following.
#include #include #include #include #include using namespace std; int main() { int age_n; std::vector candles_n; int input; cin>>age_n; while(cin >> input) candles_n.push_back(input); int largest_height = *std::max_element(candles_n.begin(), candles_n.end()); int mycount = std::count (candles_n.begin(), candles_n.end(), largest_height); cout << mycount; return 0; }