-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelectionSort.java
More file actions
75 lines (64 loc) · 2.27 KB
/
SelectionSort.java
File metadata and controls
75 lines (64 loc) · 2.27 KB
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
public class SelectionSort {
static void sort(int[] array, boolean isDesc) {
// finds the minimum element in array[i..] and swap it with array[i]
for (int i = 0; i < array.length - 1; i++) {
int index = i;
for (int j = i + 1; j < array.length; j++) {
if ((!isDesc && (array[j] < array[index])) || (isDesc && (array[j] > array[index]))) {
index = j;
}
}
swap(array, i, index);
}
}
static void swap(int[] array, int index1, int index2) {
int tmp = array[index2];
array[index2] = array[index1];
array[index1] = tmp;
}
static void sort(int[] array) {
sort(array, false);
}
static void sort(char[] array, boolean isDesc) {
// finds the minimum element in array[i..] and swap it with array[i]
for (int i = 0; i < array.length - 1; i++) {
int index = i;
for (int j = i + 1; j < array.length; j++) {
if ((!isDesc && Character.compare(array[j], array[index]) < 0)
|| (isDesc && Character.compare(array[j], array[index]) > 0)) {
index = j;
}
}
swap(array, i, index);
}
}
static void swap(char[] array, int index1, int index2) {
char tmp = array[index2];
array[index2] = array[index1];
array[index1] = tmp;
}
static void sort(char[] array) {
sort(array, false);
}
static void sort(String[] array, boolean isDesc) {
// finds the minimum element in array[i..] and swap it with array[i]
for (int i = 0; i < array.length - 1; i++) {
int index = i;
for (int j = i + 1; j < array.length; j++) {
if ((!isDesc && array[j].compareTo(array[index]) < 0)
|| (isDesc && array[j].compareTo(array[index]) > 0)) {
index = j;
}
}
swap(array, i, index);
}
}
static void swap(String[] array, int index1, int index2) {
String tmp = array[index2];
array[index2] = array[index1];
array[index1] = tmp;
}
static void sort(String[] array) {
sort(array, false);
}
}