-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSelectionSort.java
More file actions
44 lines (34 loc) · 1.17 KB
/
SelectionSort.java
File metadata and controls
44 lines (34 loc) · 1.17 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
public class SelectionSort {
private SelectionSort(){}
public static <E extends Comparable<E>> void sort(E[] arr){
// arr[0...i) 是有序的;arr[i...n) 是无序的
for(int i = 0; i < arr.length; i ++){
// 选择 arr[i...n) 中的最小值
int minIndex = i;
for(int j = i; j < arr.length; j ++){
if(arr[j].compareTo(arr[minIndex]) < 0)
minIndex = j;
}
swap(arr, i, minIndex);
}
}
private static <E> void swap(E[] arr, int i, int j){
E t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
public static void main(String[] args){
Integer[] arr = {1, 4, 2, 3, 6, 5};
SelectionSort.sort(arr);
for(int e: arr)
System.out.print(e + " ");
System.out.println();
Student[] students = {new Student("Alice", 98),
new Student("Bobo", 100),
new Student("Charles", 66)};
SelectionSort.sort(students);
for(Student student: students)
System.out.print(student + " ");
System.out.println();
}
}