排序算法-InsertSort-插入排序
来源:互联网 发布:2017年中国经济 知乎 编辑:程序博客网 时间:2024/06/06 14:05
1. 插入排序算法介绍
有一个已经有序的数据序列,要求在这个已经排好的数据序列中插入一个数,但要求插入后此数据序列仍然有序,这个时候就要用到一种新的排序方法——插入排序算法。
插入排序的基本操作就是将一个数据插入到已经排好序的有序数据中,从而得到一个新的、个数加一的有序数据,算法适用于少量数据的排序,时间复杂度为O(n^2)。是稳定的排序方法。
2. 算法流程
插入算法把要排序的数组分成两部分:第一部分包含了数组中已经排好序的数据,第二部分包含了待排序的数据。而算法的每次处理就是将无序数列的第一个元素与有序数列的元素从后往前逐个进行比较,找出插入位置,将该元素插入到有序数列的合适位置中。
示意图:
3.算法实现
3.1 降序排列
//type * pArray: 待排序数组指针//int len:数组的长度//typename type:模板库//typename type:模板库template <typename type>void InsertSortHigh2Low(type * pArray, int len);template <typename type>void InsertSortHigh2Low(type * pArray, int len){ int i, j; int temp; for (i=1; i<len; i++) { temp = pArray[i]; for (j= i-1; j>=0; j--) { if (pArray[j]<temp) { pArray[j+1] = pArray[j]; if (0==j) pArray[j] = temp; } else { pArray[j] = temp; break; } } }}
3.2 升序排列
//type * pArray: 待排序数组指针//int len:数组的长度//typename type:模板库template <typename type>void InsertSortLow2High(type * pArray, int len);template <typename type>void InsertSortLow2High(type * pArray, int len){ int i, j; int temp; for (i=1; i<len; i++) { temp = pArray[i]; for (j= i-1; j>=0; j--) { if (pArray[j]>temp) { pArray[j+1] = pArray[j]; if (0==j) pArray[j] = temp; } else { pArray[j] = temp; break; } } }}
0 0
- InsertSort 插入排序算法
- 排序算法-插入排序 insertSort
- 排序算法-InsertSort-插入排序
- 插入排序算法(InsertSort)
- 经典算法-插入排序Insertsort
- 算法学习----->Insertsort(插入排序)
- 经典排序算法(2) -插入排序 InsertSort
- 算法导论2.1-insertsort算法(插入排序)
- 算法与数据结构--插入排序(InsertSort)
- 插入排序InsertSort
- insertSort - 插入排序
- 插入排序 InsertSort
- 插入排序 InsertSort
- 插入排序(InsertSort)
- 插入排序InsertSort
- 插入排序-InsertSort
- java insertsort 插入排序
- 插入排序-insertsort
- iOS中怎么转为UTF-8
- html中的table
- SVM入门(一)至(三)Refresh
- 根据url自动下载图片的demo
- oracle 两个时间相减
- 排序算法-InsertSort-插入排序
- U盘安装Win7操作系统
- git教程
- 如何设计一门语言(一)——什么是坑(a)
- Java敏感词过滤MFC版发布
- INSERT INTO SELECT和SELECT INTO两种表复制语句
- SVM入门(四)线性分类器的求解——问题的描述Part1
- Android图片上传 Java服务器接收
- START