我對編程相當陌生,我剛開始使用java。我的任務是使用快速排序編寫程序,我設法編寫它,但它總是給我一個索引越界。任何人都可以看看我的代碼,並通過確定我所做的錯誤來幫助我嗎?謝謝用java快速排序算法(netbeans)
這是主類的代碼。
package quicksort;
public class Quicksort {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int[] x = {5,3,10,1,9,8,7,4,2,6,0};
quicksort_class q = new quicksort_class(x);
q.sort();
for(int i = 0; i < 11-1; i++)
{
System.out.println(x[i]);
}
}
}
這是quicksort_class的代碼。
public class quicksort_class {
int[] array1 = new int[11];
public quicksort_class(int[] w)
{
array1 = w;
}
public void partitionstep(int leftlimit, int rightlimit)
{
int LPointer = leftlimit;
int RPointer = rightlimit;
Random random = new Random();
int midpoint = random.nextInt(11);
int checknumber = array1[midpoint];
while(LPointer < RPointer)
{
while(array1[LPointer] <= checknumber)
{
LPointer = LPointer + 1;
}
while(array1[RPointer] >= checknumber)
{
RPointer = RPointer --;
}
swap(LPointer, RPointer);
partitionstep(leftlimit, midpoint - 1);
partitionstep(midpoint + 1, rightlimit);
}
}
public void swap(int x, int y)
{
int temp = array1[x];
array1[x] = array1[y];
array1[y] = temp;
}
public void sort()
{
partitionstep(0, array1.length - 1);
}
}
你從哪裏得到索引超出範圍異常?請打印實際的錯誤信息。 – bblincoe
中點的隨機化不能給你一個超越邊界的點嗎? – Khanser
@Khanser它不應該是因爲它停留在數組的範圍之內。 nextInt(11)將從[0 - 11)返回一個隨機值。該數組將始終爲大小11.但是,在分區時,它們應該調整它們正在查看的範圍(小於11)。 – bblincoe