步骤讲解
以此类推,得到正确的排列顺序
选择排序缺点: 时间复杂度O(n2),不管一组数是否有序,都会进行二次循环。
代码
对于整形的排序
private int [] a;
public void selectSort1(int [] a){
for (int i = 0; i <a.length ; i++) {
int minIndex = i;
for (int j = i+1; j <a.length ; j++) {
if(a[j]<a [minIndex])
minIndex = j;
}
swap(a,minIndex,i);
}
for (int i = 0; i <a.length ; i++) {
System.out.print(a[i]+" ");
}
}
private void swap(int[] x, int a, int b) {
int t = x[a];
x[a] = x[b];
x[b] = t;
}
使用泛型,对于任何类型排序
package select;
import org.junit.Test;
public class SelectSort2<E> {
/* *//* public static void main(String[] args) {
E [] a= {4,5,1,2,3};
select.SelectSort1(a);
}*/
@Test
public void test() {
Integer[] a = {4, 5, 1, 2, 3};
String[] a1 = {"A", "C", "B", "F", "D", "E"};
SelectSort1(a1);
}
public <E extends Comparable<E>> void SelectSort1(E[] a) {
for (int i = 0; i < a.length; i++) {
int minIndex = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j].compareTo(a[minIndex]) > 0)
minIndex = j;
}
if (minIndex != i) {
E temp = a[minIndex];
a[minIndex] = a[i];
a[i] = temp;
}
// swap(a,minIndex,i);
}
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
}
定义一个lessE接口,根据你自己的逻辑处理,不仅仅是增序或者降序
public interface LessE<E> {
Boolean less (E a, E b);
}
package select;
import org.junit.Test;
public class SelectSort1<E> {
private LessE<E> lessE;
private E [] a;
public SelectSort1(E[] a , LessE<E> less ){
this.a =a;
this.lessE = less;
}
public void selectSort1(E [] a){
for (int i = 0; i <a.length ; i++) {
int minIndex = i;
for (int j = i+1; j <a.length ; j++) {
if(lessE.less(a[j],a[minIndex]))
minIndex = j;
}
swap(a,minIndex,i);
}
for (int i = 0; i <a.length ; i++) {
System.out.print(a[i]+" ");
}
}
private void swap(E[] x, int a, int b) {
E t = x[a];
x[a] = x[b];
x[b] = t;
}
}
package select;
public class Main {
public static void main(String[] args) {
// Integer [] a1= {4,5,1,2,3};
String [] a1= {"a","b","d","c"};
SelectSort1<String> selectSort1 = new SelectSort1<>(a1, new LessE<String>() {
@Override
public Boolean less(String a, String b) {
if (a.compareTo(b)>0)
return true;
return false;
}
});
selectSort1.selectSort1(a1);
}
}
此外选择排序是个不稳定的排序
举个例子,序列3 2 3 1 9, 我们知道第一遍选择第1个元素3会和1交换,那么原序列中2个3的相对前后顺序就被破坏了,所以选择排序不是一个稳定的排序算法