MergeSort to find the number of inversions that do not work when trying to read from a file

I am trying to execute a mergesort implementation to find the number of inversions. It seems that the array returns the correct results for a small list of numbers that are hard-coded, but returns the wrong number when reading from a file. I suppose this has something to do with string comparison, but I can't figure out what exactly the problem is. Any insight would be helpful. Here is the (relevant) code -

public class ReadFile {


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


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

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


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

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


}




 public static int [] 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[5000];
int[] nData=new int[nLines];

    //int nData[]={1,3,5,2,4,6};


 for (int i=0; i < nLines; i++) {

    nData[ i ] = Integer.parseInt((textR.readLine()));// **Is this causing the problem?**

    }

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[]){...

}

+2
source share
1 answer

. 5 , 100000 , ½ × 100000 2= 5 × 10 9 a int. long s:

  • count ( )
  • countLeft, countRight, countMerge ( countInversions)
  • countInversions mergeAndCount
+2

All Articles