Skip to content

Commit efb77da

Browse files
authored
Add files via upload
1 parent d5197fc commit efb77da

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

Sorting/InsertionSort.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/* Insertion Sorting
2+
3+
Algorithm:
4+
Iterate from index i --> 1 to length -1
5+
Assign key = A[i];
6+
j = i - 1;
7+
Loop j >= 0 and A[j] > key
8+
A[j + 1] = A[j];
9+
j = j - 1;
10+
End Loop
11+
A[j + 1] = key;
12+
End Iterate.*/
13+
public class InsertionSort {
14+
15+
public static void main(String[] args) {
16+
17+
// input array
18+
int[] inputArray = { 6, 5, 3, 1, 8, 7, 2, 4 };
19+
int length = inputArray.length;
20+
int j = 0;
21+
22+
System.out.print("Before Sorting: ");
23+
printArray(inputArray);
24+
System.out.print("\nValues for each Iteration");
25+
//loop to show different iterations/steps
26+
for (int i = 1; i < length; i++) {
27+
j = i - 1;
28+
int key = inputArray[i];//taking the input
29+
while (j >= 0 && inputArray[j] > key) {
30+
inputArray[j + 1] = inputArray[j];//comparing the neighbour elements
31+
j = j - 1;
32+
}
33+
inputArray[j + 1] = key;
34+
System.out.println();
35+
printArray(inputArray);
36+
}
37+
38+
System.out.print("\nAfter sorting: ");//printing the sorted array
39+
printArray(inputArray);
40+
41+
}
42+
43+
private static void printArray(int[] inputArray) {
44+
for (int value : inputArray) {
45+
System.out.print(value + " ");
46+
}
47+
}
48+
49+
}

0 commit comments

Comments
 (0)