/**
* 选择排序
* 算法步骤:
* 1.首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置
* 2.再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾
* 3.重复第二步,直到所有元素均排序完毕
* 选择排序是不稳定的排序方法。
*/
public class SelectionSort {
public static void exec(int[] source){
for (int i=0;i<source.length-1;i++){
// 临时保存最小的数组下标
int minIndex = i;
// 从i+1下标开始循环比较
for (int j=i+1;j<source.length;j++){
// 更新最小数的数组下标
if (source[j]<source[minIndex]){
minIndex=j;
}
}
// 如果最小的数组下标minIndex和当前比较数组的开始下标i不相等,交互数据
if(i!=minIndex){
int tmp = source[minIndex];
source[minIndex]=source[i];
source[i]=tmp;
}
}
for (int value : source) {
System.out.print(value + " ");
}
}
public static void main(String[] args) {
int[] source = {5,4,2,3,8,4,2,9,10,1};
exec(source);
}
}