Here. All the imports are to create a random array of Integers. No loops, just recursion:
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.IntStream;
import java.util.Arrays;
public class cursedInsertSort {
public static void sort(int[] arr) {
if (arr == null || arr.length <= 1) {
return;
}
cursed_insertion_sort(arr, arr.length, 1);
}
private static void cursed_insertion_sort(int a_list[],int len,int i) {
if (i >= len) return;
cursed_insert(a_list, i, a_list[i]); // shift and insert
cursed_insertion_sort(a_list, len, i + 1);
}
private static void cursed_insert(int a_list[], int j, int val) {
if (j <= 0 || a_list[j-1] <= val) {
a_list[j] = val; // insert here
return;
}
a_list[j] = a_list[j-1]; // just keep shifting
cursed_insert(a_list, j - 1, val);
}
public static void main(String args\[\]) {
int n = 25;
int[] a = IntStream.range(0, n).map(i -> ThreadLocalRandom.current().nextInt()).toArray();ThreadLocalRandom.current().nextInt()).toArray();
System.out.println("Unsorted array");
System.out.println(Arrays.toString(a));
sort(a);
System.out.println("Sorted array");
System.out.println(Arrays.toString(a));
}
}
Output:
$ javac cursedInsertSort.java
$ java cursedInsertSort
Unsorted array
[1979090481, 1975907117, 1075830741, -941322152, -1787386922, -1214147410, -1064101530, -116915382, 1736910972, -1121809185, -896766788, 298102074, 659604714, 20876505, 235971615, 1779792957, 429619610, -1966855425, -617075915, -580772798, -1931560891, -982585117, -1713967857, 899010361, -1260583312]
Sorted array
[-1966855425, -1931560891, -1787386922, -1713967857, -1260583312, -1214147410, -1121809185, -1064101530, -982585117, -941322152, -896766788, -617075915, -580772798, -116915382, 20876505, 235971615, 298102074, 429619610, 659604714, 899010361, 1075830741, 1736910972, 1779792957, 1975907117, 1979090481]
``