import java.util.Arrays;
/**
*
* @author Administrator
* 选择排序的基本原理:(1)对于给定的一组记录,经过第一轮的比较后得到最小的记录,然后将该记录与第一个记录的位置进行交换;
* (2)接着对不包括第一个记录以外的其它记录进行第二轮比较,得到最小的记录并与第二个记录进行位置交换;
* (3)重复该过程,直到进行比较的记录只有一个时为止。
*
*选择排序的关键是每次找出最小的元素,将当前要排序的元素和最小的元素进行位置互换。
*/
public class SelectSort1 {
//用于打印数组元素
public static void printArray(int[] a){
System.out.println(Arrays.toString(a));
}
public static void selectSort(int[] a){
int n=a.length;
int temp =0; //使用temp存储每次遍历最小的数值
int flag=0; //使用flag存储每次遍历最小元素的下标
for(int i=0;i<n;i++){
temp = a[i];
flag = i;
for (int j = i+1; j < n; j++) {
if(temp>a[j]){
temp =a[j];
flag = j;
}
if(flag != i){ //找出最小元素后进行位置的互换
a[flag] =a[i];
a[i] =temp;
}
}
System.out.print("第"+i+"次:");
printArray(a);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[]={6,5,4,3,2,1};
selectSort(a);
}
}
程序运行结果:
第0次:[1, 6, 5, 4, 3, 2]
第1次:[1, 2, 6, 5, 4, 3]
第2次:[1, 2, 3, 6, 5, 4]
第3次:[1, 2, 3, 4, 6, 5]
第4次:[1, 2, 3, 4, 5, 6]
第5次:[1, 2, 3, 4, 5, 6]