问题
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 long
s:
count
(in main)countLeft, countRight, countMerge
(in countInversions)- return types of
countInversions
andmergeAndCount
来源:https://stackoverflow.com/questions/9781804/mergesort-implementation-to-find-number-of-inversions-not-working-when-trying-to