mergeSort implementation to find number of inversions not working when trying to read from a file

倾然丶 夕夏残阳落幕 提交于 2019-12-10 10:59:55

问题


Im trying to do a mergesort implementation to find the number of inversions. . The array seems to return the right results for a small list of numbers that are hard coded, but returns an incorrect number when I read from a file. I guess its something to do with string- integer comparison, but cant figure out what exactly the issue is, . Any insight would be helpful.Here's 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[]){...

}


回答1:


You are getting integer overflow. The numbers themselves might be all at most 5 digits, but since you have 100000 elements the count can reach ½ × 1000002 = 5 × 109, which slightly too big for an int. Change the following to longs:

  • count (in main)
  • countLeft, countRight, countMerge (in countInversions)
  • return types of countInversions and mergeAndCount


来源:https://stackoverflow.com/questions/9781804/mergesort-implementation-to-find-number-of-inversions-not-working-when-trying-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!