【发布时间】:2019-03-09 09:29:37
【问题描述】:
好吧好吧。我一直在研究 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);
}
}
【问题讨论】:
标签: java sorting recursion selection-sort