【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);

}

做一个优秀的程序媛
原文地址:https://www.cnblogs.com/oytt/p/13500697.html