选择排序

170 阅读1分钟
```
import java.util.Arrays;

// 选择排序
// 对与长度两个及以上的数组进行操作
// 思路:n-1 次循环 每次循环选择一个最小值放到最前面
public class SelectionSort {
    public static void main(String args[]) {
        int[] toSortArr = {4,5,1,2,6};
        int[] sortedArr = SelectionSort.selectionSort(toSortArr);
        System.out.println(Arrays.toString(sortedArr));
    }
    public static int[] selectionSort(int[] toSortArr) {
        if(toSortArr.length <= 1) {
            return toSortArr;
        }else {
            for(int i = 0 ;i < toSortArr.length - 1; i++) {
                int minIndexTemp = i;
                for(int j = i + 1; j < toSortArr.length; j++) {
                    if(toSortArr[minIndexTemp] > toSortArr[j]) {
                        minIndexTemp = j;
                    }
                }
                // exchange position
                int temp = toSortArr[i];
                toSortArr[i] = toSortArr[minIndexTemp];
                toSortArr[minIndexTemp] = temp;
            }
        }
        return toSortArr;
    }
}
```
产生的运算为(n-1)次循环,每次循环执行(n-i)次比较,执行的总次数为(n-1)*(n-2)*...* 1,等差数列,时间复杂度o(n2);
注: 时间复杂度为执行总次数的高阶项去掉系数部分,因为当n趋向于无穷大的时候,低阶项和任一固定系数皆可忽略