2013-11-01 57 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); 
}