我正在嘗試在 java 中撰寫一個快速排序函式,該函式接收一個未排序的陣列,并回傳相同的排序陣列。該演算法應該呼叫自身,直到整個陣列被排序。基本情況是子陣列范圍只有 1 個元素。只要子陣列不為 1,我們就一直在磁區的兩端呼叫快速排序
目前,我的代碼回傳以下
示例:[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;
}
}
uj5u.com熱心網友回復:
首先在swap方法中,您將索引b而不是b值放入a位置
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/411326.html
標籤:
上一篇:javaarraylist如何對與字串混合的Int值進行排序
下一篇:使用本機方法對陣列進行排序的問題
