第一个for循环从头遍历数组中的每一个元素。记录指针指向当前元素的下标。第二个for循环遍历后面的每一个元素。与前一个元素比较,如果比当前一个元素小,则指针指向该元素,依次向后遍历。第二个for循环遍历完成后,指针指向的是第二个for循环中最小的元素。交换最小元素与当前元素的位置。
每一次循环完后,都将最小的元素移到最前面。
public class 选择排序 {
/**
* 排序
*/
public static void sort(Comparable[] a){
//只需要遍历到倒数第二个元素,因为遍历到这个元素后,只需要与最后一个元素比较大小
for(int i=0;i<a.length-1;i++){
int cur=i;
for(int j=i+1;j<a.length;j++){
if(greater(a[cur],a[j])){
cur=j;
}
}
swap(a,i,cur);
}
}
/**
* 判断两个元素大小
*/
public static boolean greater(Comparable v,Comparable w){
int result=v.compareTo(w);
return result>0;
}
/**
* 交换数组中两个元素的位置
*/
public static void swap(Comparable[] a,int i,int j){
Comparable temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}