繁体   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