-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathInsertSort.java
More file actions
33 lines (29 loc) · 937 Bytes
/
InsertSort.java
File metadata and controls
33 lines (29 loc) · 937 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
public class InsertSort {
public static void main(String[] args) {
System.out.println();
System.out.println("7 5 4 3");
System.out.println();
System.out.println("5 4 7 3");
System.out.println();
int[] unsorted = {3, 7, 4, 5};
int[] result = sort(unsorted);
for (int j : result) {
System.out.print("" + j + " ");
}
}
public static int[] sort(int[] unsorted) {
for (int i = 1; i < unsorted.length; i++) {
for (int j = i; j > 0; j--) {
int jthElement = unsorted[j];
int jMinusOneElement = unsorted[j - 1];
if (jthElement < jMinusOneElement) {
unsorted[j - 1] = jthElement;
unsorted[j] = jMinusOneElement;
} else {
break;
}
}
}
return unsorted;
}
}