-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
Copy pathinsertion_sort.java
90 lines (75 loc) · 2.5 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Insertion sort for integer and string arrays
class instertion_sort {
// Integer version
public static void insertion_sort_int(int[] arr) {
int i, j, current;
// Loops through array
for (i = 1; i < arr.length; i++) {
j = i - 1;
current = arr[i];
// Loops backward from current element to find its spot
while (j >= 0 && current < arr[j]) {
arr[j + 1] = arr[j];
j--;
}
// Inserts the number in its correct place within the sorted half
arr[j + 1] = current;
}
}
// String version
public static void insertion_sort_str(String[] arr) {
int i, j;
String current;
// Loops through array
for (i = 1; i < arr.length; i++) {
j = i - 1;
current = arr[i];
// Loops backward from current element to find its spot
while (j >= 0 && current.compareToIgnoreCase(arr[j]) < 0) {
arr[j + 1] = arr[j];
j--;
}
// Inserts the string in its correct place within the sorted half
arr[j + 1] = current;
}
}
// Tests insertion_sort_int
public static void int_tester() {
int[] test_arr = {77, 52, -27, 1, 7, 0, 127, 45, 25};
// Prints original array
System.out.println("Original array: ");
for (int i : test_arr) {
System.out.println(i + " ");
}
// Sorting occurs
insertion_sort_int(test_arr);
// Prints results
System.out.println("After sort: ");
for (int i : test_arr) {
System.out.println(i + " ");
}
}
// Tests insertion_sort_string
public static void str_tester() {
String[] test_arr2 = {"hello", "hi", "tomorrow", "zoo", "kitten", "Help", "dog", "climb", "I"};
// Prints original array
System.out.println("Original array: ");
for (String str : test_arr2) {
System.out.println(str + " ");
}
// Sorting occurs
insertion_sort_str(test_arr2);
// Prints resulting array
System.out.println("After sort: ");
for (String str : test_arr2) {
System.out.println(str + " ");
}
}
// Main method calling test functions
public static void main(String[] args) {
int_tester();
System.out.println();
str_tester();
System.out.println();
}
}