Sorting algorithms - insertion sort

Direct insertion sort

 The basic idea

Trip direct insertion sort: R is inserted in the ordered regions in the process [i] is.

 

Algorithm code

1  // direct insertion sort 
2  void InsertSort ( int * ARR, int n-)
 . 3  {
 . 4      int I, J;
 . 5      int TEMP;
 . 6  
. 7      for (I = 1 ; I <n-; I ++ )
 . 8      {
 . 9          IF (ARR [ i] <ARR [i - . 1 ]) // if the i-th and the last element of the preceding sorted in reverse order, began moving 
10          {
 . 11              TEMP = ARR [i]; // remember the element 
12 is              for (J = I - . 1 ; J> = 0ARR && [J]> temp; J, )
 13 is              {
 14                  ARR [J + . 1 ] = ARR [J]; // than unity temp large rearward movement of the elements 
15              }
 16              ARR [J + . 1 ] = temp ; // until a condition is not satisfied j--, placed at a temp. 1 + J 
. 17          }
 18 is      }
 . 19 }

Analysis of Algorithms

Binary insertion sort

 The basic idea

 Direct insertion sort, when ordered regions too many elements, in order to find the insertion position may be the number of comparisons area too, the use of binary insertion method, that is a binary search to insert into position to speed up the search efficiency, but want to move elements are still the same and direct insertion sort, just to enhance the search efficiency.

 

Algorithm code

 1 //折半插入排序
 2 void BinInsertSort(int *arr, int n)
 3 {
 4     int i, j;
 5     int low, high, mid;
 6     int temp;
 7     for (i = 1; i < n; i++)
 8     {
 9         if (arr[i] < arr[i - 1]) //如果第i个和前面的已排序的最后一个元素反序时,才开始查找
10         {
11             temp = arr[i]; //将要插入的元素被temp记住
12             low = 0;
13             high = i - 1;
14 
15             while (low <= high)
16             {
17                 mid = (low + high) / 2;
18                 if (temp < arr[mid])
19                     high = mid - 1;
20                 else
21                     low = mid + 1;
22             } //找到位置high
23 
24             for (j = i - 1; j >= high + 1; j--) //将比temp大的元素统一向后移动
25             {
26                 arr[j + 1] = arr[j];
27             }
28             arr[high + 1] = temp; //在high+1处放入temp
29         }
30     }
31 }

 算法分析

折半插入排序:在R[0..i-1]中查找插入R[i]位置,折半查找的平均关键字比较次数为log2(i+1)-1,平均移动元素的次数为i/2+2,所以平均时间复杂度为:

 

折半插入排序采用折半查找,查找效率提高。但元素移动次数不变,仅仅将分散移动改为集合移动。

 

Guess you like

Origin www.cnblogs.com/WindSun/p/11360523.html