为什么我的快速排序函数没有运行



我正试图用java编写一个快速排序函数,该函数接收一个未排序的数组,并返回排序后的相同数组。该算法应该调用自己,直到对整个数组进行排序。基本情况是当子阵列范围仅为1个元素时。只要子数组不是1,我们就一直在分区的两端调用quicksort

目前,我的代码返回以下

示例:[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位置

最新更新