package com.demon.algorithm;
import java.util.Arrays;
/**
* 选择排序步骤(升序):
* 1. 找到未排序数组中的最小元素,存放到数组开头(从起始下标开始作为已排序序列)
* 2. 继续查找未排序数组,将最小元素放到已排序序列的末尾
* 3. 重复 2 步骤,直到所有元素排序完毕
* <p>
* 注意:
* 1. 当数组已经排好序时,性能最快
* 2. 当数组倒序排列时最慢,因为要做最多的循环
* 3. 选择排序稳定性差,消耗性能高
* <p>
* 时间复杂度: O(n2)
* 空间复杂度: O(1)
*
* @author Demon-HY
* @date 2019-5-6
*/
public class SelectionSort {
public static void main(String[] args) {
// 待排序的数组
int[] srcList = new int[]{3, 1, 23, 4, 23, 56, 7, 2, 64};
System.out.println("待排序数组:" + Arrays.toString(srcList));
// 排序
selectionSort(srcList);
System.out.println("已排序数组:" + Arrays.toString(srcList));
}
public static void selectionSort(int[] srcList) {
// 用来交换最小值元素的临时变量
int swap;
// 最小值元素下标
int minIndex;
// 开始下标,需要遍历源数组的每一个下标
for (int i = 0; i < srcList.length; i++) {
minIndex = i;
// 该下标每次循环需要向前挪动一位
for (int j = i + 1; j < srcList.length; j++) {
if (srcList[j] < srcList[minIndex]) {
// 更新最小值元素下标
minIndex = j;
}
}
// 如果起始下标(i)和最小值元素下标不重复,则交换两个下标的值
if (i != minIndex) {
swap = srcList[i];
srcList[i] = srcList[minIndex];
srcList[minIndex] = swap;
}
}
}
}