Okay okay. I have been working on a recursive selection sort in Java. I have done my reading, googling, stack overflowing, and am still unable to figure it out. I think the code is getting worse the more time I spend on it due to overcomplicating it. All the examples I have seen use multiple parameters, and the single parameter is throwing me off.
Below is the recursive method and the driver. The first 3 if statements are given so I am assuming required.
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);
}
}
There is some problem in your code.
at the first you use startIndex
and find good number from your array for that, then increment it at the end of code which is redundant because when function called again, it use 0 for it again. each function call has it's own variable and so the next call, function create new startIndex
and use that which is zero again.
You must pass it to function and increment at each next function call. because of this, you base check is not true anymore and it is changed to check until we get at the end of our array.
also this line of code is redundant because when we get to this line, we know that arr.lenghth()
is more than one. (however our logic of code changed and there is no need to this too)
if ( startIndex >= arr.length - 1 )
return;
return when get to base condition like 1 is better and throw exception is not necessary because when it is one, we return without going lower. (conditions always false for zero or empty array. you don't remove anything from array too)
I define recursive function as a function that sort array from start index sent to it.
This is the result:
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 + " ");
}
}
}
I hope this is what you want.