C++ insertion sort(插入排序)

来源:互联网 发布:北津学院教务网络系统 编辑:程序博客网 时间:2024/05/17 22:49

插入排序也是一种简单的排序算法。 对于一些large lists, 其效率远远没有一些高级的排序算法列入quick sort, heap sort, merge sort 那么高效。

然而插入排序也有自己的优点:

(1)实现简单

(2) 对于小的数量集, 比较高效

(3)stable(稳定的), 即 不会改变相同keys 的相对出现的顺序(does not change the relative order of elements with equal keys

(4)in-place(原位的), 即只需要空间复杂度是常数, 也即O(1), only requires a constant amount O(1) of additional memory space

(5)可以在线的排序。 i.e., can sort a list as it receives it

(6)比bubber sort, selection sort 的效率要高。 这几个都是时间复杂度为O(n^2), 最佳的case 或者接近最佳的case 的时间复杂度达到了O(n)

 

例如

The following table shows the steps for sorting the sequence {3, 7, 4, 9, 5, 2, 6, 1}. In each step, the key under consideration is underlined. The key that was moved (or left in place because it was biggest yet considered) in the previous step is shown in bold.

 

再比如下面的动态图像:

 

伪代码如下:


//Insertion sort for array based list#include <iostream>#include <ctime>#include <cstdlib> // 产生随机数#include <iomanip>using namespace std;template <class elemType>void print(elemType list[], int length);//insertion sorttemplate <class elemType>void insertionSort(elemType[], int);int main() {   int intList[100];   int num;   for (int i = 0; i < 100; i++){      num = (rand() + time(0)) %1000;      intList[i] = num;   }   cout << "intList before sorting: " << endl;   print(intList, 100);   cout << endl << endl;   insertionSort(intList, 100);   cout << "intList after insertion sort: " << endl;   print(intList, 100);   cout << endl;   system("Pause");   return 0;}template <class elemType>void print(elemType list[], int length) {   int count = 0;   for(int i = 0; i < length; i++) {      cout << setw(5) << list[i];      count++;      if(count % 10 == 0)         cout << endl;   }}template <class elemType>void insertionSort(elemType list[], int length) {  for (int firstOrder = 1; firstOrder < length; firstOrder++) {     if (list[firstOrder] < list[firstOrder - 1]) {        elemType temp = list[firstOrder]; //copy loaction - 1 to location        int location = firstOrder; //initialize location to first out of order        do {           list[location] = list[location - 1];//copy location - 1 into locations           location--;        }while(location > 0 && list[location - 1] > temp);        list[location] = temp; //copy temp into list location     }  }}


运行结果为:

0 0
原创粉丝点击