尝试实现快速排序算法

时间:2021-04-08 16:46:45

标签: java algorithm sorting quicksort

刚开始学习算法:尝试用Java实现快速排序算法。但是它在输出中没有显示任何内容尝试了很多次但找不到原因。 它没有显示任何内容。

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;
    }
}

1 个答案:

答案 0 :(得分:0)

你的问题来自分区方法。您一直卡在第二个 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);
    
相关问题