选择排序
需求:
排序前:{4,6,8,7,9,2,10,1}
排序后:{1,2,4,5,7,8,9,10}
算法设计:
Selection类:
package suanfa;
public class Selection {
//对数组a中的元素进行排序
public static void sort(Comparable[] a){
for(int i =0;i<a.length-1;i++){
int minIdex = i;
for(int j = i+1;j<a.length;j++){
if(greater(a[minIdex],a[j])){
minIdex = j;
}
}
exch(a,i,minIdex);
}
}
//比较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;
}
}
SelectionTest类:
package suanfa;
import java.util.Arrays;
public class SelectionTest {
public static void main(String[] args) {
Integer[] a={4,6,8,7,9,10,1};
Selection.sort(a);
System.out.println(Arrays.toString(a));
}
}
录制: untitled2 – Selection.java
录制文件:https://meeting.tencent.com/crm/Kwqmpbqjd6