选择排序
原理: 首先在未排序序列中找到最小(大)元素,存放到排序序列的起始(队尾)位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾(队首)。以此类推,直到所有元素均排序完毕
操作步骤:
- 以第一个元素为基准,下标index先固定在第一个元素下,
- 从index+1后面的元素循环依次跟index下标元素比较,如果找到比第一个元素小的,则下标index跑到这个小的数下面,直到第一轮结束找到数组中最小的元素标固定在最小元素的位置
- 取排好序的队列队尾元素跟当前index下标的数据比较,如果队尾位置上的元素比当前index小则呼唤,直至队列排好序。
public static void selectSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int index = i;
for (int j = i + 1; j < array.length; j++) {
if (array[j] < array[index]) {
index = j;
}
}
//{1,2,5,8,3,9,4,6,7};
if (index != i) {//如果已经是最小的,就不需要交换
int temp = array[index];
array[index] = array[i];
array[i] = temp;
}
}
}
运行:
@Test
public void testSort() {
int[] array = new int[]{3,2,5,8,1,9,4,6,7};
for (int i : array) {
System.out.print(i + " ");
}
System.out.println("\n");
selectSort(array);
for (int i : array) {
System.out.print(i + " ");
}
}
运行结果:
最坏的时间复杂度都是O(n*n)