码迷,mamicode.com
首页 > 编程语言 > 详细

插入排序(INSERTION_SORT)

时间:2015-06-18 11:32:18      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:插入排序   排序   排序算法   算法   c语言算法   

插入排序(INSERTION_SORT)

    1)原理 : 插入排序对于少量的元素排序是一个有效的算法。插入排序的工作方式像是在拿扑克牌一样,最开始的时候手里是空的,每抽到一张牌就将其在另一只手上按一定的规律排好序,直到所有的元素排列完成。

    2)C语言实现

#include<stdio.h>
#include<cstdlib>
void sortNum(int count, int *a)
{
    for (int i = 1; i < count; i++)
    {
        for (int j = 0; j < i; j++)
        {
            if (a[j] >= a[i])
            {
                //每插入一个数之后向后,把数组其他元素向后挪动
                int temp = a[i];
                for (int k = i; k > j; k--)
                {
                    a[k] = a[k - 1];
                }
                a[j] = temp;
            }
        }
    }
}

void main()
{
    int temp,count, *p;
    printf("please input the count :");
    scanf_s("%d", &count);
    p = (int *)malloc(count * 2);
    printf("\nplease input the number to be sorted : \n");
    for (int i = 0; i < count; i++)
    {
        scanf_s("%d", p+i);
    }
    sortNum(count, p);
    for (int i = 0; i < count; i++)
    {
        printf("%d ", p[i]);
    }
    system("pause");
}

    3)分析

  1. 最好情况(序列已经有序) :插入排序只需要将整个序列遍历一遍即可。故时间复杂度为O(n),为线性时间复杂度。
  2. 最坏情况(序列与需要排列的顺序相反):则每次遍历都需要将元素向后移位,时间复杂度为O(n^2)。
  3. 平均情况:随机选择n个数来进行插入排序,平均情况下,对元素A[j]来说,确定A[0~j-1]元素和A[j]的大小,次数大约在j/2次左右,因此平均时间复杂度也是O(n^2)。

插入排序(INSERTION_SORT)

标签:插入排序   排序   排序算法   算法   c语言算法   

原文地址:http://blog.csdn.net/jing_unique_da/article/details/46545595

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!