选择排序
1.每次遍历一遍数组,先把数组最小的元素拿出来放到最前面,再进行第二次遍历,再把最小的拿出来
每次选择还没有处理的元素里面最小的
循环不变量 :arr[i,n)未排序,arr[0,i)
2.时间复杂度:O(n^2)
3.1代码实现(适合于int类型数据):
public class SelectionSort {
private SelectionSort() {
}
public static void sort(int[] arr) {
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] < arr[minIndex])
minIndex = j;
}
swap(arr, i ,minIndex);
}
}
private static void swap(int[] arr,int i,int j){
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
public static void main(String[] args){
int[] arr = {1,5,2,7,4};
SelectionSort.sort(arr);
for (int i : arr)
System.out.print(i + " ");
System.out.println();
}
}
3.2 代码实现(适合于所有数据类型):
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,5,2,7,4};
SelectionSort.sort(arr);
for (int i : arr)
System.out.print(i + " ");
System.out.println();
//对特殊对象进行排序
Student[] students = {new Student("tom",55),
new Student("Bob",100),
new Student("tom",69)};
SelectionSort.sort(students);
for (Student student : students)
System.out.print(student);
System.out.println();
//测试算法性能
int n = 100000;
Integer[] arr2 = ArrayGenerator.generatorRandomArray(n,n);
long startTime = System.nanoTime();
SelectionSort.sort(arr2);
long endTime = System.nanoTime();
double time = endTime - startTime /1000000000.0;
if (!SortingHelper.isSorted(arr2))
throw new RuntimeException("SelectionSort Failed");
System.out.println("time:" + time);
}
}