-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSort.java
More file actions
31 lines (28 loc) · 943 Bytes
/
InsertionSort.java
File metadata and controls
31 lines (28 loc) · 943 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
public class InsertionSort {
public static void main(String[] args) {
String[] array = {"chores fruit", "date", "cherry", "plum", "elderberry", "apple", "orange", " preserves ",};
System.out.println("Original array:");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
sort(array);
System.out.println("\nSorted array:");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
public static void sort(String[] a) {
int n = a.length;
for (int i = 1; i < n; i++) {
for (int j = i; j > 0; j--) {
if (a[j-1].compareTo(a[j]) > 0) {
String temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
} else {
break;
}
}
}
}
}