mergeSort实现,用于查找尝试从文件读取时无效的反转次数

我试图做一个mergesort实现来查找反转次数。 。 该数组似乎返回了一个硬编码的小数字列表的正确结果,但是当我从文件中读取时返回的数字不正确。 我猜它与字符串整数比较有关,但无法弄清楚究竟是什么问题,。 任何见解都会有所帮助。这是(相关)代码 –

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

}

你正在获得整数溢出。 数字本身可能最多为5位数,但由于您有100000个元素,因此计数可达到½×100000 2 = 5×10 9 ,这对于int有点太大了。 将以下内容更改为long s:

  • count (主)
  • countLeft, countRight, countMerge (在countInversions中)
  • 返回countInversionsmergeAndCount类型