排序算法-插入排序(Insert sort)

  • 算法思想

  插入排序使用的是增量方法:将待排序数组A[1,n]分为有序部分A[1,j-1]和无序部分A[j,n],关键步骤是将无序部分中的元素逐个插入到有序部分中,使有序部分不断增加,最终使整个数组有序。

  • 伪代码

  //插入排序数组A[1,n]

  InsertSot(A,n)

    for i←2 to n

      do key←A[i]//待插入的数

         j←i-1

        while j>0 and A[j]<temp//从待插入的数开始比较

         do A[j+1]=A[j]

            j←j-1

         A[j+1]←key

  • 算法效率分析

     最好情况:如果序列原来就有序,因为每次循环只需比较一次,此时该算法运行时间最少。

         T(n)= O(n)

          最坏情况:如果序列原来是逆序,因为每次循环必须将key与有序部分的每个元素进行比较。

        T(n)= 1+2+...n-1=n(n-1)/2=O(n2)

  • Code
 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 int main()
 5 {
 6     FILE* fp = NULL;//输入文件指针
 7     int *array = NULL;//排序数组指针
 8     int key;//待插入元素
 9     int i,j;
10     int N;//数组元素个数
11     if(!(fp = fopen("Input.txt","r")))//打开输入文件
12         return -1;
13     fscanf(fp,"%d",&N);
14     array = (int*)malloc(sizeof(int)*N);//分配内存空间
15     for(i=0; i!=N; i++)
16         fscanf(fp,"%d",array+i);
17     for(i=1; i!=N; i++)
18     { 
19         key = array[i];
20         j=i-1;
21         while(j>=0 && key<array[j])
22         {
23             array[j+1] = array[j];
24             j--;
25         }
26         array[j+1] = key;
27     }
28 
29     for(i=0; i!=N; i++)
30         printf("%d ",array[i]);
31     printf("\n");
32     fclose(fp);
33     free(array);
34     getchar();
35     return 0;
36 }
  • Running result

    Input:10   

       3 5 4 -1 2 34 53 10 7 12

    Output:

      

      

 

 

        

posted on 2013-04-11 21:37  shaolw  阅读(379)  评论(1编辑  收藏  举报

导航