以前写过排序算法,但是主要写的是算法的概念和实现代码,本次主要写下算法的执行过程。
好了,还是先回忆下概念。选择排序是指每次循环都把剩余数据中最小的(最大的)数找出来,从而在进过多轮循环之后得出有序数据。选择排序的时间复杂度为O(n*n).
假设有一组数组,{99,67,82,43,12,26,18,55},则其选择从小到大的排序过程如下:
{99,67,82,43,12,26,18,55}
第一次循环:{67,99,82,43,12,26,18,55}
{43,99,82,67,12,26,18,55}
{12,99,82,67,43,26,18,55}
第二次循环:{12,99,82,67,43,26,18,55}
{12,82,99,67,43,26,18,55}
{12,67,99,82,43,26,18,55}
{12,43,99,82,67,26,18,55}
{12,26,99,82,67,43,18,55}
{12,18,99,82,67,43,26,55}
第三次循环:{12,18,99,82,67,43,26,55}
{12,18,82,99,67,43,26,55}
{12,18,67,99,82,43,26,55}
{12,18,43,99,82,67,26,55}
{12,18,26,99,82,67,43,55}
第四次循环:{12,18,26,99,82,67,43,55}
{12,18,26,82,99,67,43,55}
{12,18,26,67,99,82,43,55}
{12,18,26,43,99,82,67,55}
第五次循环:{12,18,26,43,99,82,67,55}
{12,18,26,43,82,99,67,55}
{12,18,26,43,67,99,82,55}
{12,18,26,43,55,99,82,67}
第六次循环:{12,18,26,43,55,99,82,67}
{12,18,26,43,55,82,99,67}
{12,18,26,43,55,67,99,82}
第七次循环:{12,18,26,43,55,67,99,82}
{12,18,26,43,55,67,82,99}
第八次循环:{12,18,26,43,55,67,82,99}
至此,排序完成,可以看出选择排序是不稳定排序。
下面是选择排序的代码实现:
public class MainTest { public static void main(String[] args){ int[] arr = {10,9,8,7,6,5,4,3,2,1}; selectingSort(arr); for (int i : arr){ System.out.println(i); } } public static void selectingSort(int[] arr){ int arrLength = arr.length; for (int i=0; i<arrLength; i++){ int minIndex = i; for (int j=i+1; j<arrLength; j++){ if (arr[j]<arr[minIndex]){ minIndex = j; } } exchange(arr, i, minIndex); } } private static void exchange(int[] arr, int nowIndex, int minIndex){ int num = arr[nowIndex]; arr[nowIndex] = arr[minIndex]; arr[minIndex] = num; } }