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];
}
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");
BufferedReader textR= new BufferedReader(fr);
int nLines=readLines();
System.out.println("Number of lines"+nLines);
int[] nData=new int[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;
while(br.readLine()!=null){
numLines++;
}
System.out.println("Number of lines readLines"+numLines);
return numLines;
}
public static int countInversions(int num[]){...
}
source
share