-
Notifications
You must be signed in to change notification settings - Fork 0
/
InsertionSort.java
40 lines (34 loc) · 950 Bytes
/
InsertionSort.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
40
package chapter02;
public class InsertionSort {
// Main implementation.
public static void sort(int[] A) {
for (int j = 1; j < A.length; j++) {
int key = A[j];
int i = j - 1;
while (i >= 0 && A[i] > key) {
A[i + 1] = A[i];
i--;
}
A[i + 1] = key;
}
}
// exercise 2.1-2
public static void sortNonDecreasing(int[] A) {
for (int j = A.length - 2; j >= 0; j--) {
int key = A[j];
int i = j + 1;
while (i < A.length && A[i] < key) {
A[i - 1] = A[i];
i++;
}
A[i - 1] = key;
}
}
// exercise 2.1-3
public static int linearSearch(int[] A, int v) {
for (int i = 0; i < A.length; i++)
if (A[i] == v)
return i;
return -1;
}
}