为什么我的快速排序函数不是 运行?

Why is my quicksort function not running?

我正在尝试在 java 中编写一个快速排序函数,它接收一个未排序的数组,returns 相同的数组已排序。该算法应该在整个数组排序之前调用自身。基本情况是子数组范围仅为 1 个元素时。只要子数组不为 1,我们就会在分区的两端继续调用快速排序

目前,我的代码returns如下

示例: [5,2,3,1] 预期输出: [1,2,3,5] 输出: [3,2,3,5]

有人可以帮我找出错误吗?谢谢!

这是我的代码:

class Solution {
    
    public int[] sortArray(int[] nums) {
        return quickSort(nums, 0, nums.length-1);
    }
    
    // 1. recursive method
    public int[] quickSort(int[] arr, int start, int end){

        // recurse: if array is more than one element, quicksort both left and right partitions
          // get pivot
        if (end-start >= 1) {
        int partition = sort(arr, start, end);
        
        quickSort(arr, start, partition);
        quickSort(arr, partition+1, end);
        }
        
        return arr;
    }
    
    // 2. swap method
    public void swap(int[] arr, int a, int b){
        int temp = arr[a];
        arr[a] = b;
        arr[b] = temp;
    }
    
    // 3. find pivot method
    public int findPivot(int min, int max){
        int random_int = (int)Math.floor(Math.random()*(max-min+1)+min);
        return random_int;
    }
    
    /* 4. sorting method  
              finds pivot value, places it to the end of the range 
              
              compares each element in the range to the pivot value and swaps the items 
              with the pivot index if the items are less than the pivot value, then moves pivot index to the right
              at the end of the loop, all items less than pivot are to the left of the pivot index
              
              end of loop: swap pivot index with pivot (currently at the right end of the range)
              
              method returns pivot index
              
              5.   8.   2.   3
            s/pI             p
    */
    
    public int sort(int[] arr, int start, int end){
       // find pivot value
        int pivot = findPivot(start, end);
        // place pivot at the end of the sorting range
        swap(arr, end, pivot);
        
        // pivot index starts out at the start
        int pivotIndex = start;
        
        // loop through start to (end -1) and make appropriate swaps
        for (int i= start; i<= end-1; i++){
            if (arr[i] < arr[end]) {    // comparing current and pivot (pivot is in start)
                // swap with pivot index, increase pivot index
                swap (arr, i, pivotIndex);
                pivotIndex++;
            }
        }
        // once loop is done, swap pivot index with pivot
        swap(arr, pivotIndex, end);
        return pivotIndex;
    }
}

首先,在 swap 方法中,您将 b 的索引而不是 b 值放入 a 位置