-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertion.java
More file actions
51 lines (43 loc) · 1.35 KB
/
Copy pathInsertion.java
File metadata and controls
51 lines (43 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*The interface you implement should take the number of elements from the user and then enter
the elements one by one. You must print the contents of the arrays for the outermost loop at each
pass of the sorting algorithm.
*/
import java.util.Scanner;
public class Insertion {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("Enter the elements: ");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
System.out.println("Array before sorting: ");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
// |----------------------------------------------------------------------------------|
for (int i = 1; i < n; i++) {
int j = i ;
while (j > 0 && arr[j-1] > arr[j]) {
int temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
j=j-1;
}
// |----------------------------------------------------------------------------------|
System.out.println("Array after pass " + i + ": ");
for (int k = 0; k < n; k++) {
System.out.print(arr[k] + " ");
}
System.out.println();
}
// |----------------------------------------------------------------------------------|
System.out.println("Array after sorting: ");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}