八大排序算法之-选择排序 java代码

来源:互联网 发布:路由器怎么映射端口 编辑:程序博客网 时间:2024/06/09 18:14
import java.util.Arrays;/** * Created by Administrator on 2017/8/2. */public class directSelectSort_select {//比较+交换    public static void main(String args[]) {        int[] arr = { 6, 9, 1, 3, 1, 2, 2, 5, 6, 1, 3, 5, 9, 7, 2, 5, 6, 1, 9 };        //[1, 1, 1, 1, 2, 2, 2, 3, 3, 5, 5, 5, 6, 6, 6, 7, 9, 9, 9]        selectSort(arr,0,arr.length-1);        System.out.println(Arrays.toString(arr));    }    /*算法思想:    * 1.从带排序的序列中找到最小的元素序列号,判断是否为当前序列号的第一个,如果不是,进行交换    * 2.从余下n-1个元素列表中执行1*/    /*时间复杂度:O(n^2)    * 空间复杂度:O(1)    * 稳定性:不稳定*/    private static void selectSort(int[] arr, int start, int end) {        for (int i = 0; i<=end; i++) {            int minIndex = i;            for (int j = i; j<=end; j++) {                if (arr[minIndex]>arr[j]) {                    minIndex = j;                }            }            if (minIndex!=i) {                swap(arr,minIndex,i);            }        }    }    private static void swap(int[] arr, int minIndex, int i) {        int tmp = arr[i];        arr[i] = arr[minIndex];        arr[minIndex] = tmp;    }}