2010-06-02 95 views
2

我必須實現快速排序。從Programming Pearls這裏是代碼:快速排序實現中的問題

public class Quick{ 
    public static void quicksort(int x[], int l, int u) 
    { 
     if (l>=u) 
      return; 
     int t = x[l]; 
     int i = l; 
     int j = u; 

     do 
     { 
      i++; 
     } while (i<=u && x[i]<t); 

     do 
     { 
      j--; 
      if (i>=j) break; 
     } while (x[j]>t); 

     swap(x, i, j); 
     swap(x, l, j); 

     quicksort(x, l , j-1); 
     quicksort(x, j+1, u ); 
    } 

    public static void main(String[]args) 
    { 
     int x[] = new int[]{55,41,59,26,53,58,97,93}; 
     quicksort(x, 0, x.length-1); 
     for (int i=0; i<x.length; i++) 
     { 
      System.out.println(x[i]); 
     } 
    } 

    public static void swap(int x[], int i, int j) 
    { 
     int s = x[i]; 
     x[i] = x[j]; 
     x[j] = s; 
    } 
} 

它不起作用。這裏輸出:

59 
41 
55 
26 
53 
97 
58 
93 

它爲什麼不起作用?

+1

是的,它不看它整理得很好...... – VoodooChild 2010-06-02 07:11:55

+0

嘗試正確格式化你的代碼 - 這使得它更容易閱讀和調試 – 2010-06-02 09:20:34

回答

3

應該是:

int t=x[l]; 
int i=l; 
-> int j=u + 1; 

此外,您錯誤地翻譯的僞代碼:這是在C#(非常相似,C,只是改變了數組聲明):

public static class Sort 
{ 
    public static void quicksort(int[] x, int l, int u) 
    { 
     if (l >= u) 
      return; 

     int t = x[l]; 
     int i = l; 
     int j = u + 1; 

     while (true) // In C, make this while(1) 
     { 
      do 
      { 
       i++; 
      } while (i <= u && x[i] < t); 

      do 
      { 
       j--; 
      } while (x[j] > t); 

      if (i >= j) 
       break; 

      swap(x, i, j); 
     } 

     swap(x, l, j); 

     quicksort(x, l, j - 1); 
     quicksort(x, j + 1, u); 
    } 


    public static void swap(int[] x, int i, int j) 
    { 
     int s = x[i]; 
     x[i] = x[j]; 
     x[j] = s; 
    } 

呼叫與此:

static void Main(string[] args) 
    { 
     int[] x = new int[] { 55, 41, 59, 26, 53, 58, 97, 93 }; 

     Sort.quicksort(x, 0, x.Length - 1); 
     for (int i = 0; i < x.Length; i++) 
     { 
      Console.WriteLine(x[i]); 
     } 
    } 

產地:

26 
41 
53 
55 
58 
59 
93 
97 
+3

哇!閱讀所有代碼+1! – 2010-06-02 07:13:46

+0

老兄,你必須分享如何在回答時很容易發現這個sh * t的祕密:) – VoodooChild 2010-06-02 07:14:45

+0

不起作用我已經改變了,但是 – 2010-06-02 07:17:30

0

看起來好像已經回答了。

因爲它在算法標籤我想說 - 我碰到this neat website它顯示正在進行排序。

檢查出來,我相信你一定會喜歡它:)