簡體   English   中英

嘗試實現快速排序算法

[英]trying to implement Quicksort Algorithm

剛開始學習算法:嘗試用Java實現快速排序算法。 但是在output中沒有顯示任何內容,但嘗試了很多次但找不到原因。
它沒有顯示任何東西。

public class Try {

    public static void main(String[] args) {
        int []arr= {22,9,8,45,28,7,1};
        int len = arr.length;
        quicksort(arr, 0, len-1); 
        for(int i = 0; i<len; i++)
            System.out.print(arr[i]+" ");
    }

    static void quicksort(int [] arr, int low, int high) {
        if (low < high) {
            int index = partition(arr, low, high);
            quicksort(arr, low, index -1);
            quicksort(arr, index+1, high);
        }
    }

    static int partition(int [] arr, int low, int high) {
        int pivot = arr[low]; 
        int i = low;
        int j = high;
        while(i<=j) {
            while(arr[i]<pivot) i++;
            while(arr[j]>pivot) j--;
        
            if(i<=j) {
                // swapping i with j 
                int temp = arr[i];  
                arr[i] = arr[j];
                arr[j] = temp;
            }
            //swapping pivot(low) with j when i<j 
            int temp = arr[low];
            arr[low] = arr[j];
            arr[j] = temp;
        }
        return j;
    }
}

您的問題來自分區方法。 您一直卡在第二個 while 循環中。 你應該用一個循環來做,這里有一個例子(我個人更喜歡使用 for 循環):

int pivot = arr[high];  
int i = (low - 1);  // Index of smaller element and indicates the 
                   // right position of pivot found so far

for (int j = low; j <= high- 1; j++)
{
     // If current element is smaller than the pivot
     if (arr[j] < pivot)
     {
         i++;    // increment index of smaller element
         int temp = arr[i];
         arr[i] = arr[j];
         arr[j] = temp;
     }
 }
    int temp = arr[i + 1];
    arr[i + 1] = arr[high];
    arr[high] = temp;
    return (i + 1);
    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM