2014-02-05 84 views
1

我對編程相當陌生,我剛開始使用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); 
} 
} 
+2

你從哪裏得到索引超出範圍異常?請打印實際的錯誤信息。 – bblincoe

+0

中點的隨機化不能給你一個超越邊界的點嗎? – Khanser

+0

@Khanser它不應該是因爲它停留在數組的範圍之內。 nextInt(11)將從[0 - 11)返回一個隨機值。該數組將始終爲大小11.但是,在分區時,它們應該調整它們正在查看的範圍(小於11)。 – bblincoe

回答

3

midpoint值應根據您的leftLimitrightLimit計算。它不應該是基於固定值11的隨機值。

+0

看起來他們實際上選擇了一個隨機中點。 – Inbl

+1

正確,更新的措辭。我相信他們需要將它們的隨機值基於有限數組的當前大小(基於左右限制)。畢竟他們正在對數組進行分區。 – bblincoe