2016-11-07 65 views
0

出于某种原因,我的数组的中间元素仍然无序......我不知道为什么,但我只是中间元素仍然未排序

public class QuickSort { 

    public int a[]; 

    public QuickSort(int[] a) { 
     this.a = a; 
    } 

    private void swap(int pos1, int pos2) { 
     int t = a[pos1]; 
     a[pos1] = a[pos2]; 
     a[pos2] = t; 
    } 

    private int partition(int low, int high) { 
     int i = low, j = low + 1, pivot = low; 
     while (j < high) { 
      if (a[j] <= a[pivot]) { 
       swap(++i, j); 
      } 
      j++; 
     } 
     swap(i, pivot); 
     return i; 
    } 

    private void sort(int low, int high) { 
     int i; 
     if (low >= high) 
      return; 
     else { 
      i = partition(low, high); 
      sort(i + 1, high); 
      sort(low, i - 1); 
     } 
    } 

    public String toString() { 
     StringBuilder sb = new StringBuilder(""); 
     for (int i : a) { 
      sb.append(i); 
      sb.append("\n"); 
     } 

     return sb.toString(); 
    } 

    private static int[] generateRandomNumbers(int s) { 

     int a[] = new int[s]; 

     for (int i = 0; i < s; i++) { 
      a[i] = new Random().nextInt(50); 
     } 

     return a; 
    } 

    public static void main(String args[]) { 

     Scanner sc = new Scanner(System.in); 
     System.out.println("Enter the size of elements"); 
     int s = sc.nextInt(); 

     QuickSort obj = new QuickSort(generateRandomNumbers(s)); 

     System.out.println(obj.toString()); 

     obj.sort(0, s - 1); 

     System.out.println("\n"); 
     System.out.println(obj.toString()); 
    } 

} 

数组充满了随机生成的数字,这是一个标准的快速排序算法 任何帮助,将不胜感激,我是一个新手程序员,试图调试的时间太长了这段代码...

+1

你可以给你使用这个与和O的一个数组的例子本安输出? –

+0

我随机生成数组...... ill编辑我的问题以添加整个代码... –

+0

您的支点是第一个元素。它不应该在中间更多吗? – TedTrippin

回答

0

修改

swap(i+1, pivot); 
return i+1; 

int i = low-1, j = low, pivot = high; 

if (low < high) 
     { 
      i = partition(low, high); 
      sort(i + 1, high); 
      sort(low, i - 1); 
     } 

这些更改后完美的作品。

+0

谢谢...对不起,我的声誉太低... –

+0

没问题总是乐意帮助新手程序员喜欢我的自我。如果解决了您的问题,请将其标记为答案 – Arthas

0

或者只是改变了“<”到“< =”作为其不检查高元......

while (j <= high) { 
+0

谢谢!我无法相信自己犯了这样一个愚蠢的错误......对不起来,我的声望太低了...... –

0

,我发现我的错误.... 它应该是

while (j <= high) 

代替

(j < high) 
相关问题