Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f79fd9a

Browse files
insertionShort implement
1 parent b1bdba8 commit f79fd9a

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

‎Shorting/insertionShort.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
public class insertionShort {
2+
public static void main(String[] args) {
3+
int[] arr = {20, 13, 10, 4, 2, 46, 8};
4+
int size = arr.length;
5+
6+
System.out.print("Before sorting: ");
7+
for (int num : arr) {
8+
System.out.print(num + " ");
9+
}
10+
11+
// Insertion Sort Algorithm
12+
for (int i = 1; i < size; i++) {
13+
int key = arr[i]; // The element to be inserted
14+
int j = i - 1;
15+
16+
// Shift elements of arr[0..i-1], that are greater than key, to one position ahead
17+
while (j >= 0 && arr[j] > key) {
18+
arr[j + 1] = arr[j];
19+
j = j - 1;
20+
}
21+
arr[j + 1] = key; // Insert the key at the correct position
22+
}
23+
24+
System.out.println();
25+
System.out.print("After sorting: ");
26+
for (int num : arr) {
27+
System.out.print(num + " ");
28+
}
29+
}
30+
31+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /