[英]Recursive Selection Sorting (Java Eclipse Neon 2)
好吧好吧。 我一直在用Java進行遞歸選擇排序。 我已經完成閱讀,谷歌搜索,堆棧溢出的工作,但仍然無法弄清楚。 我認為,由於過於復雜,我花在代碼上的時間越多,代碼就會變得越糟。 我看到的所有示例都使用多個參數,而單個參數讓我失望。
下面是遞歸方法和驅動程序。 給出了前3個if語句,因此我假設是必需的。
public static void selectionSort_Rec(int[] arr)
{
if(arr == null) throw new NullPointerException();
if(arr.length == 0) throw new IllegalArgumentException();
if(arr.length == 1) return;
int startIndex = 0;
if ( startIndex >= arr.length - 1 )
return;
int minIndex = startIndex;
for ( int index = startIndex + 1; index < arr.length; index++ )
{
if (arr[index] < arr[minIndex] )
minIndex = index;
}
int temp = arr[startIndex];
arr[startIndex] = arr[minIndex];
arr[minIndex] = temp;
startIndex++;
selectionSort_Rec(arr);
}
// Driver method
public static void main(String args[])
{
int arr[] = {3, 1, 5, 2, 7, 0};
// Calling function
selectionSort_Rec(arr);
for(int i :arr){
System.out.print(i);
}
}
您的代碼中存在一些問題。
首先,您使用startIndex
並從數組中找到合適的數字,然后在代碼的末尾將其遞增,這是多余的,因為再次調用函數時,它將再次使用0。 每個函數調用都有其自己的變量,因此在下一次調用時,函數創建新的startIndex
並再次使用為零的變量。
您必須將其傳遞給函數,並在每次下一個函數調用時遞增。 因此,您的基本檢查不再成立,並且更改為檢查,直到我們到達數組末尾為止。
這行代碼也是多余的,因為當我們到達這一行時,我們知道arr.lenghth()
不止一個。 (但是我們的代碼邏輯發生了變化,也不需要這樣做)
if ( startIndex >= arr.length - 1 )
return;
當達到基本條件(例如1)更好並且不需要拋出異常時返回,因為當它為1時,我們不降低就返回。 (條件對於零或空數組始終為false。您也不會從數組中刪除任何內容)
我將遞歸函數定義為對從發送給它的開始索引進行數組排序的函數。
結果如下:
public class GFG
{
public static void selectionSort_Rec(int[] arr) {
selectionSortHelper(arr, 0);
}
static void selectionSortHelper(int[] arr, int startIndex) {
if (startIndex >= arr.length)
return;
int minIndex = startIndex;
for (int index = startIndex + 1; index < arr.length; index++)
{
if (arr[index] < arr[minIndex])
minIndex = index;
}
int temp = arr[startIndex];
arr[startIndex] = arr[minIndex];
arr[minIndex] = temp;
selectionSortHelper(arr, startIndex + 1);
}
// Driver method
public static void main(String args[]) {
int arr[] = {3, 1, 5, 2, 7, 0};
// Calling function
selectionSort_Rec(arr);
for (int i : arr)
{
System.out.print(i + " ");
}
}
}
我希望這就是你想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.