选择排序:
原理:(1)每一次遍历的过程中,都假定第一个索引处的元素是最小值,和其他索引处的值依次进行比较,如果当前索引处的值大于其他某个索引处的值,则假定其他某个索引处的值为最小值,最后可以找到最小值所在的索引。
(2)交换第一个索引处和最小值所在的索引处的值。
时间复杂度: O(n^2)
Java代码实现(附测试案例):
package day01;
public class Selection {
public static void sort(Comparable[] a) {
for (int i = 0; i <= a.length - 2; i++) {
//定义一个变量,记录最小元素所在的索引,默认为参与选择排序的第一个元素所在的位置
int minIndex=i;
for (int j = i + 1; j < a.length; j++) {
//需要比较最小索引minIndex处的值和j索引处的值
if (greater(a[minIndex], a[j])) {
minIndex=j;
}
}
exch(a,i,minIndex);
}
}
//比较v元素是否大于w元素
private static boolean greater(Comparable v, Comparable w) {
return v.compareTo(w)>0;
}
//数组元素i和j交换位置
private static void exch(Comparable[] a, int i, int j) {
Comparable temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
package test;
import java.util.Arrays;
import day01.Selection;
public class SelectionTest {
public static void main(String[] args) {
Integer[] arr = {
4, 6, 8, 7, 9, 2, 10, 1};
Selection.sort(arr);
System.out.println(Arrays.toString(arr));
}
}