插入排序

来源:互联网 发布:淘宝有违禁词吗 编辑:程序博客网 时间:2024/05/30 05:14

参考1:

插入排序是最简单最直观的排序算法了,它的依据是:遍历到第N个元素的时候前面的N-1个元素已经是排序好的了,那么就查找前面的N-1个元素把这第N个元素放在合适的位置,如此下去直到遍历完序列的元素为止.
算法的复杂度也是简单的,排序第一个需要1的复杂度,排序第二个需要2的复杂度,因此整个的复杂度就是
1 + 2 + 3 + ... + N = O(N ^ 2)的复杂度.

 

直接插入排序(straight insertion sort)的作法是:

  每次从无序表中取出第一个元素,把它插入到有序表的合适位置,使有序表仍然有序。

  第一趟比较前两个数,然后把第二个数按大小插入到有序表中; 第二趟把第三个数据与前两个数从前向后扫描,把第三个数按大小插入到有序表中;依次进行下去,进行了(n-1)趟扫描以后就完成了整个排序过程。

  直接插入排序属于稳定的排序,时间复杂性为o(n^2),空间复杂度为O(1)。 

C语言版

[cpp] view plaincopy
  1. #include <stdio.h>;  
  2.   
  3.   
  4. void InsertSort(int array[],unsigned int n)  
  5.  {  
  6.     int i,j;  
  7.     int temp;  
  8.     for(i=1;i<n;i++)  
  9.     {  
  10.       temp = array[i];//store the original sorted array in temp  
  11.       for(j=i ; j>0 && temp < array[j-1] ; j--)//compare the new array with temp(maybe -1?)  
  12.       {  
  13.           array[j]=array[j-1];//all larger elements are moved one pot to the right  
  14.       }  
  15.       array[j]=temp;//此时的j已经是空位的j  
  16.     }  
  17.  }  
  18.   
  19.   
  20. int main(void)  
  21. {  
  22.     int arr[]={1,5,2,4,3,8,6,7,9};  
  23.     int count=sizeof(arr)/sizeof(int);  
  24.       
  25.     InsertSort(arr,count);  
  26.   
  27.     int k;  
  28.     for(k=0;k<count;k++)  
  29.     {  
  30.         printf("%d",arr[k]);  
  31.     }  
  32.     return 0;  
  33. }  




原创粉丝点击