-
Notifications
You must be signed in to change notification settings - Fork 273
Expand file tree
/
Copy pathInsertionSort.java
More file actions
37 lines (30 loc) · 832 Bytes
/
Copy pathInsertionSort.java
File metadata and controls
37 lines (30 loc) · 832 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
26
27
28
29
30
31
32
33
34
35
36
37
public class InsertionSort {
public static void main(String[] args) {
int[] array = {9, 0, 4, 2, 3, 8, 7, 1, 6, 5};
System.out.println("Insertion Sort:");
System.out.println("Unsorted array:");
printArray(array);
array = insertionSort(array);
System.out.println("Sorted array:");
printArray(array);
}
public static int[] insertionSort(int[] array) {
int key, aux;
for (int i = 0; i < array.length; i++) {
key = array[i];
aux = i - 1;
while (aux >= 0 && array[aux] > key) {
array[aux + 1] = array[aux];
aux -= 1;
}
array[aux + 1] = key;
}
return array;
}
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + ", ");
}
System.out.println("");
}
}