2012-03-20 19 views
2

我試圖做一個mergesort實現來找到反轉次數。 。該數組似乎返回了硬編碼數字的小列表的正確結果,但是當我從文件中讀取時返回的數字不正確。我想它與字符串整數比較有關,但無法弄清楚究竟是什麼問題。任何有識之士將helpful.Here的的(相關)代碼 -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[]){... 

}

回答

2

你得到整數溢出。數字本身可能最多隻有5位數,但由於您有100000個元素,因此計數可能會達到½×100000 = 5×10 ,這對於int來說稍大。更改以下到long S:

  • count(主)
  • countLeft, countRight, countMerge(在countInversions)
  • countInversions返回類型和mergeAndCount
+0

:由於一噸!工作就像一個魅力,我會立即刪除我對這個問題的評論! – KodeSeeker 2012-03-20 10:19:24

+0

和其他人,有沒有一種方法發送私人消息在stackoverflow? – KodeSeeker 2012-03-20 10:41:51

相關問題