选择排序
步骤讲解
以此类推,得到正确的排列顺序
选择排序缺点: 时间复杂度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);
}
}