美文网首页
选择排序

选择排序

作者: SDBridge | 来源:发表于2017-03-09 17:06 被阅读0次

    选择排序 升序

    基本思想:
    对于N记录的序列,让第1个记录和其余 N-1个记录进行比较,选择其中最小的数值与第1个记录交换位置,

    然后 让第2个记录和其余 N-2个记录进行比较,选择其中最小的数值与第2个记录交换位置

    然后 让第3个记录和其余 N-3个记录进行比较,选择其中最小的数值与第3个记录交换位置。

    一直到让第N-1个记录和其余 1个记录进行比较,选择其中最小的数值与第N-1个记录交换位置

    void selectSort(long a[],long n){
       
       long temp  = 0;
       
       for ( long i = 0; i< n-1; i++) {
           
           for (long j=i+1; j < n; j++) {//当i= 0是,a[0]将会与a[1]~a[n-1]进行比较
               
               if (a[j] <  a[i]) {
                   
                   temp =a[i];
                   
                   a[i] = a[j];
                   
                   a[j] = temp;
                   
               }
           }
       }
    }
    

    最好的情况下时间复杂度O(n);
    平均时间复杂度O(n^2);
    最坏的情况下的时间复杂度O(n^2)

    相关文章

      网友评论

          本文标题:选择排序

          本文链接:https://www.haomeiwen.com/subject/bzfggttx.html