[英]Recursion using a for loop for selection sort
我有一個遞歸選擇排序方法,並在另一種方法中進行了初始遞歸調用。 但是我在遞歸方法中使用了 for 循環。 如果我有 for 循環,它仍然是遞歸方法嗎? 如何在沒有 for 循環的情況下遞歸地實現選擇排序?
private static void SelectionSortRecursive(int[] Array, int n) // sorted in descending order recursively
{
if (n >= Array.Length - 1)
return;
int max = n;
for (int i = n + 1; i < Array.Length; i++)
{
if (Array[i] > Array[max])
max = i;
}
swap(Array, n, max);
SelectionSortRecursive(Array, n + 1);
}
排序算法正常工作並正確排序。
將您的for
循環留在...仍然是遞歸的,因為您已經有一個遞歸調用,並且在遞歸中添加任何數量的非遞歸仍然會留下遞歸。
在沒有for
循環的情況下實現上述內容......它可以完成。 @Emaro 的答案是正確的,因為它在代碼中沒有顯式的for
循環,但他使用的 LINQ 仍然是對數組的隱式有限非遞歸迭代......即循環。
所以如果你真的不想要一個循環,你可以用遞歸替換它。
private static void SelectionSortRecursive(int[] arr, int n)
{
if (n >= arr.Length - 1)
return;
int max = n;
Max(n + 1);
swap(arr, n, max);
SelectionSortRecursive(arr, n + 1);
void Max(int i)
{
if (i == arr.Length)
return;
if (arr[i] > arr[max])
max = i;
Max(i + 1);
}
}
這是一個奇怪的解決方案,不是我個人寫的,但你仍然可以。
使用 linq 方法 Max() 選擇最大的整數。 使用 Skip() 我們確保在要求最大值時跳過已經排序的元素。 此代碼沒有循環。
private static void SelectionSortRecursive(int[] Array, int n)
{
if (n >= Array.Length - 1)
return;
var max = System.Array.IndexOf(Array, Array.Skip(n).Max());
swap(Array, n, max);
SelectionSortRecursive(Array, n + 1);
}
如果代碼不能以這種方式工作,請確保包含using System.Linq;
在文件的頂部。
編輯
修復 indexOf 和跳過值。
您需要鍵入 System.Array,因為您的本地變量也稱為 Array。 本地變量應該是較低的駝峰式。 樣本:
private static void SelectionSortRecursive(int[] array, int n)
{
if (n >= array.Length - 1)
return;
var max = Array.IndexOf(array, array.Skip(n).Max());
swap(array, n, max);
SelectionSortRecursive(array, n + 1);
}
您的解決方案是遞歸的,因為為了確定每個階段的值,您正在對方法本身進行一次調用。 更進一步,您可以嘗試使for loop
邏輯本身也是遞歸的。
像這樣的東西:
private static void SelectionSortRecursive(int[] Array, int n) // sorted in descending order recursively
{
if (n >= Array.Length - 1)
return;
int max = n;
max = Compare(Array, max, n+1);
swap(Array, n, max);
SelectionSortRecursive(Array, n + 1);
}
private static int Compare(int[] arr, int max, int i)
{
if(i == arr.Length)
return max;
if (arr[i] > arr[max])
max = i;
max = Compare(arr,max,++i);
return max;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.