-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSort.java
More file actions
25 lines (23 loc) · 820 Bytes
/
Copy pathInsertionSort.java
File metadata and controls
25 lines (23 loc) · 820 Bytes
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
public class InsertionSort {
public static void main(String[] args) {
int[] arr = { 1, 0, 9, 8, 4, 8, 2 };
insertionSort(arr);
for (int i : arr) {
System.out.print(i + " ");
}
}
// The insertion sort algorithm sorts an array by inserting elements one by one by comaaring elements on the left and shifts them right if they are greater than the current element.
// Less efficient than bubble sort and selection sort.
public static int[] insertionSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int temp = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > temp) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}
return arr;
}
}