Here is the code to recursively sort an unique array of integers in Java. public static int[] recursiveSelectionSort(int[] list, int n) { if (n == list.length - 1) { return list; } int temp, lowestIndex = n; for (int i = n + 1; i < list.length; i++) { if (list[i] < list[lowestIndex]) { lowestIndex = i; } } temp = list[n]; list[n] = list[lowestIndex]; list[lowestIndex] = temp; return recursiveSelectionSort(list, n+1); } To test this method, use the code below.
public static void main() { int[] arr = {-1, 10, -999, 20, 1, 2, 3, -100, 200, 20000, 99999, -99999}; System.out.println(Arrays.toString(recursiveSelectionSort(arr, 0))); } Note: Imports java.util.Arrays; is needed at the top of the class file. Happy coding. Recently, there have been some requests on code that sorts an array of unique integers in ascending order using recursion. public static int[] recursiveBubbleSort(int[] list, int n) { if (n == 1) { return list; //finished sorting } int temp; for (int i = 0; i < n-1; i++) { if (list[i+1] < list[i]) { temp = list[i]; list[i] = list[i+1]; list[i+1] = temp; } } return recursiveBubbleSort(list, n-1); } To test this method, use the code below.
public static void main(String[] args) { int[] arr = {-1, 10, -999, 20, 1, 2, 3, -100, 200, 20000, 99999, -99999}; System.out.println(Arrays.toString(recursiveBubbleSort(arr, arr.length))); } Note: Imports java.util.Arrays; is needed at the top of the class file. Happy coding. |