This code sorts and prints the random numbers which are what I want. What I am missing is the words that go before the numbers. I am new to java but am more proficient in Python. I want each random number when printed out to say the following:
result[0] = _
result[1] = _
result[2] = _
result[3] = _
Without having to put each of these in the code one by one. In Python, the code would be the following which would print all of it out.
print(“result[“,I,”] =“, result[I])
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Size of Random Number");
int n = input.nextInt();
Random random = new Random();
int[] result = random.ints(n, -n, n).toArray();
Arrays.stream(result).forEach(System.out::println);
System.out.println("\n");
int len = result.length;
System.out.println("Insertion Sort");
for(int i=1; i<len; i++){
int j;
int key = result[i];
for (j=i-1; (j >= 0 && result[j] > key); j--) {
result[j + 1] = result[j];
result[j+1] = key;
for( i = 0; i < len; i++){
System.out.println("result[" + (i) + "] =" );
Arrays.stream(result).forEach(System.out::println);
System.out.println("\n");
}
}
}
}
The problem is that you have put the print statement inside the nested loop. Also, you are printing the whole array on each iteration of the nested loop. Just take that out and print only one element in one iteration.
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Size of Random Number: ");
int n = input.nextInt();
Random random = new Random();
int[] result = random.ints(n, -n, n).toArray();
Arrays.stream(result).forEach(System.out::println);
System.out.println("\n");
// Insertion sort
int len = result.length;
for (int i = 1; i < len; ++i) {
int key = result[i];
int j = i - 1;
while (j >= 0 && result[j] > key) {
result[j + 1] = result[j];
j = j - 1;
}
result[j + 1] = key;
}
System.out.println("After sorting: ");
for (int i = 0; i < len; i++) {
System.out.println("result[" + (i) + "] =" + result[i]);
}
}
}
A sample run:
Enter Size of Random Number: 5
0
-5
-3
2
1
After sorting:
result[0] =-5
result[1] =-3
result[2] =0
result[3] =1
result[4] =2
Note: I've also corrected your sorting logic. There are hundreds of tutorials available on the internet to learn about Insertion Sort e.g. you can check this one.