Skip to content

Commit 6e5f29c

Browse files
Merge pull request #30 from HetuKariya/Insertion-Sort
Added Insertion-Sort.java file Please add Hacktoberfest Accepted tag in this PR
2 parents 5c70f65 + c84d8f3 commit 6e5f29c

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

java/InsertionSort.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import java.util.*;
2+
3+
public class InsertionSort {
4+
5+
public static void main(String[] args) {
6+
Scanner scan = new Scanner(System.in);
7+
int n = scan.nextInt();
8+
int[] arr = new int[n];
9+
for (int i = 0; i < n; i++) {
10+
arr[i] = scan.nextInt();
11+
}
12+
insertionSort(arr);
13+
System.out.println(Arrays.toString(arr));
14+
}
15+
16+
public static void insertionSort(int[] arr) {
17+
for (int i = 0; i < arr.length - 1; i++) {
18+
for (int j = i + 1; j > 0; j--) {
19+
if (arr[j] < arr[j - 1]) {
20+
swap(arr, j, j - 1);
21+
} else {
22+
break;
23+
}
24+
}
25+
}
26+
}
27+
28+
public static void swap(int[] arr, int i, int correct) {
29+
int temp = arr[i];
30+
arr[i] = arr[correct];
31+
arr[correct] = temp;
32+
}
33+
}

0 commit comments

Comments
 (0)