forked from srishilesh/Data-Structure-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsertion_sort.java
39 lines (39 loc) · 1.05 KB
/
Insertion_sort.java
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
// "static void main" must be defined in a public class.
public class Main {
public static void main(String[] args) {
int[] A = {31, 41, 59, 26, 41, 58};
A = sortAscending(A);
print(A);
A = sortDescending(A);
print(A);
}
public static void print(int[] arr) {
for (int val : arr)
System.out.print(val + " ");
System.out.println();
}
public static int[] sortAscending(int[] A) {
for (int i = 1; i < A.length; i ++) {
int key = A[i];
int j = i - 1;
while (j >= 0 && A[j] > key) {
A[j + 1] = A[j];
j = j - 1;
}
A[j + 1] = key;
}
return A;
}
public static int[] sortDescending(int[] A) {
for (int i = 1; i < A.length; i ++) {
int key = A[i];
int j = i - 1;
while (j >= 0 && A[j] < key) {
A[j + 1] = A[j];
j = j - 1;
}
A[j + 1] = key;
}
return A;
}
}