数据结构之选择排序

  • 基本原理

       对于给定的一组记录,经过第一轮比较后得到最小的记录,然后将该记录与第一个记录的位置进行交换;接着对不包括第一个记录以外的其他记录进行第二轮比较,得到最小的纪录并与第二个记录进行位置交换;重复该过程,直到进行比较的记录只有一个时为止。

  • 程序如下
public class Test{
    public static void selectSort(int[] a){
        int temp = 0;    //用来保存每轮中的最小值
        int flag = 0;    //用来保存每轮中最小值的下标
        for(int i=0;i<a.length;i++){
            temp = a[i];
            flag = i;
            for(int j=i+1;j<length;j++){
                if(a[j]<temp){
                    temp = a[j];
                    flag = j;                    
                }
            }
            if(flag != i){
                a[flag] = a[i];
                a[i] = temp;
            }
        }
    }
    public static void main(String[] args){
        int [] a = {7,6,4,8,9,3,2};
        selectSort(a);
        for(int i=0;i<a.length;i++){
            System.out.print(a[i]+" ");
        }
    }
}

程序结果

  • 算法分析
  1. 最好时间:O(n2)
  2. 平均时间:O(n2)
  3. 最坏时间:O(n2)
  4. 辅助存储:O(1)
  5. 稳定性:不稳定
原文地址:https://www.cnblogs.com/jiqianqian/p/6626488.html