zoukankan      html  css  js  c++  java
  • 【2】算法排序 (直接插入排序)

    思想:

      将待排序的数据插入到前面已排好序的序列中、

    时间复杂度:

      O(n^2)

     看循环几次,一次就O(n) n此就O(n^2)、

    #include <stdio.h>
    #include <stdlib.h>
    
    void PrintSort(int * a, int n)
    {
            int i;
            for(i=0; i<n; i++) {
                    printf(" %d ", a[i]);
            }
            printf("
    ");
    }
    
    // 基础版
    void InsertSortBase(int * a, int n)
    {
            int i, j, temp;
            for(i=1; i<n; i++) {
                    if(a[i] < a[i-1]) {
                            j = i-1;
                            temp = a[i];
                            while(j>-1 && temp <a[j]) {
                                    a[j+1] = a[j];
                                    j--;
                            }
                            a[j+1] = temp;
                    }
            }
    }
    
    // 标准版
    void InsertSortStandard(int * a, int n)
    {
            int i, j, temp;
            for(i=1; i<n; i++) {
                    temp = a[i];
                    for(j=i; j-1>=0 && temp < a[j-1]; j--) {
                            a[j] = a[j-1];
                    }
                    a[j] = temp;
            }
    }
    
    // 升级版
    void InsertSortPlus(int * a, int n)
    {
            int i, j, temp;
            for(i=1; i<n; i++) {
                    temp = a[i];
                    for(j=i-1; j>-1 && temp < a[j]; j--) {
                            a[j+1] = a[j];
                    }
                    a[j+1] = temp;
            }
    }
    
    /*
    解析:
    (1) i=1
            for(i=1; i<n; i++) {
                    ...
            }
            数组下标从0开始
            i从1开始,也就是第二个元素的下标,a[1]=23
            tmp存储的是被比较的无序序列,
            tmp之前的元素都是已经比较好的有序序列
    
    (2) j=i-1 
            for(j=i-1; j>-1 && temp < a[j]; j--) {
                    ...
            }
            因为j代表的是有序元素,
            因为是升序,tmp比之前的小就要替换掉,继续找
            直到找 >=tmp的值 才停止
    
    (3) a[j+1] = temp;
            这里j+1与上面的j+1不同,因为j--
    */
    void main()
    {
            int n = 10;
            int a[] = {11, 67, 9, 12, 1, 5, 32, 2, 78, 6};
            printf("基础版本:
    ");
            InsertSortBase(a, n);
            PrintSort(a, n);
    
            printf("标准版本:
    ");
            InsertSortStandard(a, n);
            PrintSort(a, n);
    
            printf("升级版本:
    ");
            InsertSortPlus(a, n);
            PrintSort(a, n);
    
    }

    做一个优秀的程序媛
  • 相关阅读:
    JavaScript没有块级作用域
    JavaScript数据类型
    接口
    Linux用户与组别的操作
    解决 macOS 下 SSH 空闲一段时间后自动断开
    Excel 系列一 之 账户类长数字打开不截断与完全显示
    怎样花两年时间去面试一个人
    北京大学硕士学位论文模板
    Mysql: 图解 inner join、left join、right join、full outer join、union、union all的区别
    刷 LeetCode 时再学习 Python 中引用
  • 原文地址:https://www.cnblogs.com/oytt/p/13500697.html
Copyright © 2011-2022 走看看