C++ insertion sort(插入排序)

插入排序也是一种简单的排序算法。 对于一些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 sort
template <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
     }
  }
}





运行结果为:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值