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 } }}
运行结果为:
- (C#)插入排序 Insertion Sort
- [C++] 插入排序法 (Insertion sort)
- 插入排序(insertion sort)
- insertion sort 插入排序
- 插入排序(Insertion Sort)
- 插入排序 Insertion Sort
- 插入排序Insertion sort
- 插入排序 (Insertion Sort)
- 插入排序Insertion sort
- 插入排序 Insertion Sort
- 插入排序 insertion sort
- 插入排序 insertion sort
- 插入排序Insertion sort
- 插入排序 Insertion sort
- 插入排序 Insertion Sort
- 插入排序-----Insertion Sort
- INSERTION-SORT插入排序
- 插入排序Insertion Sort
- POJ 1742 - Coins (dp 多重背包)
- DSP开发中遇到的问题 - 类指针未初始化后果
- C++ 对象模型 学习笔记(1)
- Adobe RIA 开发工程师认证考试大纲
- min2440 uart中断模式(非fifo模式)
- C++ insertion sort(插入排序)
- top命令详解
- A*算法详细讲解(转)
- copyWithZone 对象的自定义拷贝 (深and浅)
- Mongodb在Ubuntu下的安装
- Android开发者必知的开发资源
- UI读取本地数据库
- Flyweight - 享元模式
- POJ-2506--Tiling (递推+大数运算)