简单选择排序

选择排序

基本思想

选择排序(Selection-sort)在要排序的一组数中,选出最小(或最大)的一个数于第1个位置的数交换;以此类推再剩余的数中再继续找最小(或最大)

时间复杂度O(\(n^2\))

代码

public class SelectionSort {

public static void selectionSort(int[] arrays) {
int length = arrays.length;
for (int i = 0; i < length; i++) {

int min = i;
// find the first, second, third ... smallest value
for (int j = i + 1; j < length; j++) {
if (arrays[j] < arrays[min]) {
min = j; // record the index
}
}

// swap the smallest value with the value in position 'i'
int temp = arrays[i];
arrays[i] = arrays[min];
arrays[min] = temp;
}

}
}