原理图
算法---选择排序-java实现---复制黏贴本博客到eclipse,运行即可看到结果。
/** * * @ClassName: SelctionSort * @Description: 选择排序-正序(从小到大排序) * @author szren * @date 2018年5月30日 下午3:26:37 * *原理示意图: * 原始数据: 8 2 6 1 7 5 3 9 4 * * i=0 1|2 6 8 7 5 3 9 4 --找到最小值1下标为【3】,8和1交换位置 * i=2 1 2|6 8 7 5 3 9 4 --找到最小值2下标为【1】,不用交换位置 * i=2 1 2 3|8 7 5 6 9 4 --找到最小值3下标为【6】,6和3交换位置 * i=3 1 2 3 4|7 5 6 9 8 --找到最小值4下标为【8】,8和4交换位置 * i=4 1 2 3 4 5|7 6 9 8 --找到最小值5下标为【5】,7和5交换位置 * i=5 1 2 3 4 5 6|7 9 8 --找到最小值6下标为【6】,7和6交换位置 * i=6 1 2 3 4 5 6 7|9 8 --找到最小值7下标为【6】,不用交换位置 * i=7 1 2 3 4 5 6 7 8|9 --找到最小值8下标为【8】,9和8交换位置 * * 选择排序的时间复杂度:简单选择排序的比较次数与序列的初始排序无关。 * 假设待排序的序列有 N 个元素,则比较次数永远都是N (N - 1) / 2。 * 简单排序的时间复杂度为 O(N2)。 * 移动次数与序列的初始排序有关。当序列正序时,移动次数最少,为 0。 * * */
import java.util.Arrays;public class SelctionSort {public static void main(String[] args) {int aa[]={8, 2, 6 ,1, 7, 5, 3, 9, 4};System.out.println("数组长度"+aa.length);System.out.println("数组初始顺序::"+Arrays.toString(aa));select_sort(aa,aa.length);System.out.println("选择排序后的顺序 shunxu::"+Arrays.toString(aa));}private static void select_sort(int array[],int lenth){ for(int i=0;i<lenth-1;i++){ int minIndex = i;//最小值下标 //计算最小值得下标,不做交换 for(int j=i+1;j<lenth;j++){ if(array[j]<array[minIndex]){ minIndex = j; } } //判断是否需要交换位置 if(minIndex != i){ int temp = array[i]; array[i] = array[minIndex]; array[minIndex] = temp; } }}}