2013-11-01 59 views
0

對於論壇來說,剛剛有一個簡短的問題。 我想弄清楚如何遞歸地編寫插入排序算法。 遞歸對我來說仍然很混亂。陣列在數組上遞歸插入排序出界

當我運行我的程序時,我收到一個數組超出界限的異常,並想知道究竟是什麼導致這個以及爲什麼。

我插入25個整數:25 67 13 98 30 22 47 52 11 20 76 13 9 53 86 21 7 45 68 29 18 93 44 50 62

import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.util.Scanner; 


class ArrayIns { 
private int[] a; 
private int nElems; 

public ArrayIns(int max) { 
    a = new int[max]; 
    nElems = 0; 
} 

public void insert(int value) { 
    a[nElems] = value; 
    nElems++; 
} 

public void display() { 
    for (int j = 0; j < nElems; j++) { 
     System.out.print(a[j] + " "); 
    } 
    System.out.println(""); 
} 

public void insertionSort() { 
    insertSortRecursive(nElems - 1); 
} 

private void insertSortRecursive(int index) { 
    int i; 
    if (index < 1) { 
    } else { 
     insertSortRecursive(index - 1); 

     int key = a[index]; 
     i = index - 1; 

     while(index >= 0 && a[i] > key) { 
      a[i+1] = a[i]; 
      i = i - 1; 
     } // while 
    } // else 
} // End of recursiveSort 
} // ArrayIns 

class InsertSortApp { 
public static void main(String[] args) throws FileNotFoundException { 
    int maxSize = 50; 
    ArrayIns arr; 
    arr = new ArrayIns(maxSize); 

    Scanner inputFile; 

    inputFile = new Scanner (new FileReader("int.dat")); 

    while(inputFile.hasNext()) { 
     int in = inputFile.nextInt(); 
     arr.insert(in); 
    } 

    arr.display(); 

    inputFile.close(); 
} 
} // End of insertsortapp 
+1

當你發佈有關異常這樣的問題,它可以幫助我們很多,如果你把東西,如堆棧跟蹤(修剪出無用位),或在錯誤的行來自例外的標題/消息。 – Nava2

回答

1

您還沒有調用排序函數但是,所以問題不在於你的遞歸算法。我認爲它與你的文件閱讀器同時循環,它增加了超過50個「整數」。

最好的辦法是打印一個計數器,看看它經過多少個循環(省略插入來測試你的while循環)。

嘗試:

inputFile = new Scanner (new FileReader("int.dat")); 

while(inputFile.hasNextInt()) { 
    int in = inputFile.nextInt(); 
    arr.insert(in); 
}