插入算法
来源:互联网 发布:游侠对战平台mac版 编辑:程序博客网 时间:2024/05/16 06:41
插入算法
相当于每次从桌面上抽一张扑克牌然后插入到手上已经排好顺序的牌中
由于前面的数字都已经排序好了,所以每次判断完以后将前面比较大的数字往后移动一位即可,最终在空缺的位置不上key
源代码:(按降序)
// 插入排序算法// 插入的那个数前面的所有数字都已经排序好#include<iostream>using namespace std;int main() { int n; int arr[1000]; cin >> n; for (int i = 0; i < n; ++i) cin >> arr[i]; int index, key; for (int j = 1; j < n; ++j) { index = j - 1; key = arr[j]; while (index >= 0 && arr[index] > key) { arr[index + 1] = arr[index]; index--; } arr[index + 1] = key; } for (int i = 0; i < n; ++i) cout << arr[i] << " "; cout << endl; return 0;}
Input:
5
4 3 1 5 2
Output:
1 2 3 4 5
源代码:(按升序)
// 按升序进行排序#include<iostream>using namespace std;int main() { int n; int arr[1000]; cin >> n; for (int i = 0; i < n; ++i) cin >> arr[i]; int index, key; for (int j = n - 2; j >= 0; j--) { index = j + 1; key = arr[j]; while (index < n && arr[index] < key) { arr[index - 1] = arr[index]; index++; } arr[--index] = key; // 注意不是index++ } for (int i = 0; i < n; ++i) cout << arr[i] << " "; cout << endl; return 0;}
0 0
- 插入算法
- 插入算法
- 插入算法
- 插入算法
- 插入算法
- 插入算法
- 插入算法
- 插入算法
- 看伪码写算法-插入算法
- 排序算法-插入算法
- 算法----插入排序算法
- 排序算法-插入算法
- 排序算法-插入算法
- [算法] 插入排序,直接插入
- 插入算法(直接插入,二分插入,希尔)
- C++插入算法及二分插入算法
- 排序算法---直接插入算法
- 算法导论-插入排序算法
- oracle从入门到精通の2-启动与关闭数据库实例
- 【Java进阶一】理解封装
- 整理RHEL 6以上的NFS配置
- 235. Lowest Common Ancestor of a Binary Search Tree
- 【leetcode】11. Container With Most Water
- 插入算法
- android拍照
- CentOS 6.5 下安装 Redis 2.8.7
- matlab中三种计算程序运行时间方法
- Ubuntu 16.04 x64搭建GitLab服务器操作笔记
- 高级搜索技巧 笔记
- 2014.08.25 大二开始
- ubuntu16.04安装mysql和mysql-workbench(通过deb包)
- Python: 渐进猜数字游戏 <1> 代码、测试与猜数字