基础算法 —— 插入排序
2011-08-29 14:58
246 查看
参考书籍:《算法导论》第二版
算法基础 —— 插入排序算法
《算法导论》第二版书中一来就提到了插入排序算法,以扑克牌摸牌来作为比喻,刚开始按照伪代码编写时,
容易忽略一个问题,即用临时变量来实现数组中数据的交换问题。由于该算法确实是算法中最容易理解与掌
握的,所以不作过多解释,以下是代码
算法基础 —— 插入排序算法
《算法导论》第二版书中一来就提到了插入排序算法,以扑克牌摸牌来作为比喻,刚开始按照伪代码编写时,
容易忽略一个问题,即用临时变量来实现数组中数据的交换问题。由于该算法确实是算法中最容易理解与掌
握的,所以不作过多解释,以下是代码
#include <iostream> #include <stdlib.h> #include <math.h> using namespace std; int main(int argc, char *argv[]) { int array_test[] = {5, 4, 3, 2, 1, 0}; // 测试数组 int key = 0; // 关键值 int temp = 0; // 临时变量 // 时间复杂度:n^2 for(int j = 1; j < 6; j++ ) { key = array_test[j]; for(int i = j - 1; i >= 0; i-- ) { if( array_test[i] > key ) { // 交换数据 temp = array_test[i + 1]; array_test[i + 1] = array_test[i]; array_test[i] = temp; } } } // 输出排序后数组 for( int i = 0; i < 6; i++ ) cout << array_test[i] << " "; cout << endl; ::system("Pause"); return 0; }
相关文章推荐
- 算法基础:排序(一)——选择排序、插入排序、Shell排序——Python实现
- 基础算法之排序(3)--插入排序
- 算法基础:排序之插入排序
- 算法导论(一)2、算法基础-插入排序 java
- 一步一步复习数据结构和算法基础-插入排序(2)
- 【基础算法】-- 插入排序
- 算法基础 (插入排序、合并排序算法)
- 数据结构与算法——三种基础排序算法C#实现(冒泡排序、选择排序、插入排序)
- 从零开始-基础算法篇-插入排序
- 算法基础1——插入排序
- 算法基础1—插入排序
- 【算法基础】插入排序
- 算法基础--插入排序递归版
- 算法基础 2.1插入排序
- 数据结构基础算法整理归纳:插入排序(三)
- java 算法基础之六插入排序与冒泡排序
- 基础算法----找出集合中最大和值的子数组,插入排序,找出数组中出现最多的元素
- java基础算法之插入排序
- 算法基础之插入排序,选择排序
- python实现基础排序算法之(插入排序)