Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7668833
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T15:27:26+00:00 2026-05-31T15:27:26+00:00

I’m taking an online class on Algorithms and trying to implement a mergesort implementation

  • 0

I’m taking an online class on Algorithms and trying to implement a mergesort implementation of finding the number of inversions in a list of numbers. But, I cant figure what Im doing wrong with my implementation as the number of inversions returned is significantly lower than the number I get while doing a brute force approach. Ive placed my implementation of the mergesort approach below

 /**
   * 
  */

 package com.JavaReference;

 import java.io.BufferedReader;
import java.io.FileReader;
 import java.io.IOException;

public class ReadFile {


public static void main(String args[]){
    int count=0;
    Integer n[];


int i=0;
    try{
    n=OpenFile();
    int num[] = new int[n.length];

    for (i=0;i<n.length;i++){
        num[i]=n[i].intValue();
    //  System.out.println( "Num"+num[i]);
    }
    count=countInversions(num);


    }
    catch(IOException e){
        e.printStackTrace();
    }

    System.out.println(" The number of inversions"+count);


}




 public static Integer[] OpenFile()throws IOException{

    FileReader fr=new FileReader("C:/IntegerArray.txt");// to put in file name.

BufferedReader textR= new BufferedReader(fr);
int nLines=readLines();
System.out.println("Number of lines"+nLines);

Integer[] nData=new Integer[nLines];
for (int i=0; i < nLines; i++) {
    nData[ i ] = Integer.parseInt((textR.readLine()));

    }
textR.close();

return nData;


}

public static int readLines() throws IOException{


FileReader fr=new FileReader("C:/IntegerArray.txt");
BufferedReader br=new BufferedReader(fr);


int numLines=0;
//String aLine;

while(br.readLine()!=null){
    numLines++;
}
System.out.println("Number of lines readLines"+numLines);
return numLines;

}

public static int countInversions(int num[]){

int countLeft,countRight,countMerge;
int mid=num.length/2,k;


if (num.length<=1){

    return 0;// Number of inversions will be zero for an array of this size.
}

int left[]=new int[mid];
int right[]=new int [num.length-mid];


for (k=0;k<mid;k++){
    left[k]=num[k];
}

for (k=0;k<mid;k++){
    right[k]=num[mid+k];
}

countLeft=countInversions(left);
countRight=countInversions(right);

int[] result=new int[num.length];
countMerge=mergeAndCount(left,right,result);
/*
 * Assign it back to original array.
 */
for (k=0;k<num.length;k++){
    num[k]=result[k];
}

return(countLeft+countRight+countMerge);
}
private static int mergeAndCount(int left[],int right[],int result[]){
int count=0;
int a=0,b=0,i,k=0;
while((a<left.length)&&(b<right.length)){

    if(left[a]<right[b]){
        result[k]=left[a++];// No inversions in this case.

    }
    else{// There are inversions.

        result[k]=right[b++];
        count+=left.length-a;
    }
    k++;

    // When we finish iterating through a.

if(a==left.length){
    for (i=b;i<right.length;i++){
        result[k++]=right[b];

    }

    }
else{
    for (i=a;i<left.length;i++){

    }
}






}


return count;
  }
  }

I’m a beginner in Java and Algorithms so any insightful suggestions would be great!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T15:27:27+00:00Added an answer on May 31, 2026 at 3:27 pm

    I found two bugs:

    • In countInversions(), when num is split into left and right you assume right has m elements. When num.length is odd, however, it will be m + 1 elements. The solution is to use right.length instead of m.
    • In mergeAndCount(), handling of the bit where one subarray is empty and the other one still has some elements is not done correctly.

    Side note:
    There is absolutely no reason to use Integer in your program, except for the Integer.parseInt() method (which, by the way, returns an int).

    Corrected code:

    /**
    *
    */
    
    package com.JavaReference;
    
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    
    public class ReadFile {
    
        public static void main(String args[]){
            int count=0;
            Integer n[];
    
            int i=0;
            try{
                n=OpenFile();
                int num[] = new int[n.length];
    
                for (i=0;i<n.length;i++){
                    num[i]=n[i].intValue();
                    // System.out.println( "Num"+num[i]);
                }
                count=countInversions(num);
    
            }
            catch(IOException e){
                e.printStackTrace();
            }
    
            System.out.println(" The number of inversions"+count);
    
        }
    
        public static Integer[] OpenFile()throws IOException{
    
            FileReader fr=new FileReader("C:/IntegerArray.txt");// to put in file name.
    
            BufferedReader textR= new BufferedReader(fr);
            int nLines=readLines();
            System.out.println("Number of lines"+nLines);
    
            Integer[] nData=new Integer[nLines];
            for (int i=0; i < nLines; i++) {
                nData[ i ] = Integer.parseInt((textR.readLine()));
    
            }
            textR.close();
    
            return nData;
    
        }
    
        public static int readLines() throws IOException{
    
            FileReader fr=new FileReader("C:/IntegerArray.txt");
            BufferedReader br=new BufferedReader(fr);
    
            int numLines=0;
            //String aLine;
    
            while(br.readLine()!=null){
                numLines++;
            }
            System.out.println("Number of lines readLines"+numLines);
            return numLines;
    
        }
    
        public static int countInversions(int num[]){
    
            int countLeft,countRight,countMerge;
            int mid=num.length/2,k;
    
            if (num.length<=1){
    
                return 0;// Number of inversions will be zero for an array of this size.
            }
    
            int left[]=new int[mid];
            int right[]=new int [num.length-mid];
    
            for (k=0;k<mid;k++){
                left[k]=num[k];
            }
    
            // BUG 1: you can't assume right.length == m
            for (k=0;k<right.length;k++){
                right[k]=num[mid+k];
            }
    
            countLeft=countInversions(left);
            countRight=countInversions(right);
    
            int[] result=new int[num.length];
            countMerge=mergeAndCount(left,right,result);
            /*
            * Assign it back to original array.
            */
            for (k=0;k<num.length;k++){
                num[k]=result[k];
            }
    
            return(countLeft+countRight+countMerge);
        }
        private static int mergeAndCount(int left[],int right[],int result[]){
            int count=0;
            int a=0,b=0,i,k=0;
            while((a<left.length)&&(b<right.length)){
    
                if(left[a]<right[b]){
                    result[k]=left[a++];// No inversions in this case.
    
                }
                else{// There are inversions.
    
                    result[k]=right[b++];
                    count+=left.length-a;
                }
                k++;
            }
    
            // BUG 2: Merging of leftovers should be done like this
            while (a < left.length)
            {
                result[k++] = left[a++];
            }
            while (b < right.length)
            {
                result[k++] = right[b++];
            }
    
            return count;
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
Seemingly simple, but I cannot find anything relevant on the web. What is the
I have a French site that I want to parse, but am running into
I am doing a simple coin flipping experiment for class that involves flipping a
I am trying to render a haml file in a javascript response like so:
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.