-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsertion Sort
39 lines (30 loc) · 891 Bytes
/
Insertion Sort
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
package DataS;
public class InsertionSort {
public static void main(String[] args) {
int[] arr = {54, 33, 27, 12, 10, 11, 70};
System.out.println("Array before sorting:");
printArray(arr);
insertionSort(arr);
System.out.println("");
System.out.println("Array after sorting:");
printArray(arr);
}
static void insertionSort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}