import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int i, temp, n, j ,num, array[], counter, k;
Scanner input = new Scanner(System.in);
num = input.nextInt();
array = new int[num];
n = array.length;
temp = 0;
for (counter = 0; counter < num; counter++)
array[counter] = input.nextInt();
for (i = 1; i < array.length; i++) {
for (j = i; j > 0; j--) {
if (array[j - 1] > array[j]) {
temp = array[j];
array[j] = array[j - 1];
array[j - 1] = temp;
}
for(k=0; k<n; k++)System.out.print(array[k]+ " ");
System.out.print("\n");
}
}
}
}
The code above is for insertion sorting an array. For example,
INPUT:
8
8 4 3 7 6 5 2 1
EXPECTED OUTPUT:
1 4 3 7 6 5 2 8
1 2 3 7 6 5 4 8
1 2 3 4 6 5 7 8
1 2 3 4 5 6 7 8
ACTUAL OUTPUT:
1 4 3 7 6 5 2 8
1 2 3 7 6 5 4 8
1 2 3 7 6 5 4 8
1 2 3 4 6 5 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
The code works in some sense but I would like to remove all the duplicates. In other words, only print if the swap happens. Anyone can help? Thank you so much.
EDIT: When an already-sorted array is passed to the argument, the output should be nothing instead of printing the already-sorted array. For example,
INPUT:
5
1 2 3 4 5
OUTPUT:
ifwhere the swap happens ;)