zoukankan
html css js c++ java
插入排序之直接插入排序
直接插入排序
时间复杂度O(n^2)
附加空间O(1)
稳定排序
#define _CRT_SECURE_NO_WARNINGS #include <iostream> using namespace std; #define LEN 8 // 有LEN个元素要排 struct Record { // 为了考察排序的稳定性,定义元素是结构体类型 int key; int otherinfo; }; void InsertSort(Record *arr, int length) // length是要排序的元素的个数,0号单元除外 { for (int i = 2; i <= length; i++) { if (arr[i - 1].key > arr[i].key) { // 若判断时改为>=,则是不稳定排序,下同 arr[0] = arr[i]; arr[i] = arr[i - 1]; int j; for (j = i - 2; arr[j].key > arr[0].key; j--) arr[j + 1] = arr[j]; arr[j + 1] = arr[0]; } } } int main(void) { freopen("in.txt", "r", stdin); Record a[LEN + 1] = {0}; for (int i = 1; i <= LEN; i++) cin >> a[i].key >> a[i].otherinfo; InsertSort(a, LEN); for (int i = 1; i <= LEN; i++) cout << a[i].key << '\t' << a[i].otherinfo << endl; return 0; } /* in.txt: 49 1 38 0 65 0 97 0 76 0 13 0 27 0 49 2 out: 13 0 27 0 38 0 49 1 49 2 65 0 76 0 97 0 */
若排序的函数写成下面这样:
void InsertSort(Record *arr, int length) // length是要排序的元素的个数,0号单元除外 { for (int i = 2; i <= length; i++) { arr[0] = arr[i]; // 当当前比较的元素比前一个大时(前面的都已排好序),可直接continue,以免复制去又复制来 int j; for (j = i - 1; arr[j].key > arr[0].key; j--) arr[j + 1] = arr[j]; arr[j + 1] = arr[0]; } }
代码是简洁了些,但有些微妙的缺陷,如注释所示。
比如排
12 27
用第二种要浪费两次复制。
查看全文
相关阅读:
oracle单行函数 之 转换函数
oracle单行函数 之 时间函数
oracle单行函数 之 数字函数
oracle单行函数 之 字符函数
oracle 之 如何链接别人电脑的oracle
轻应用介绍
Web 目录枚举与遍历漏洞解决
接口测试工具(Postman)
Tomcat 编码不一致导致乱码
持久化配置管理 diamond 使用简介
原文地址:https://www.cnblogs.com/jjtx/p/2533471.html
最新文章
Linux 输出重定向>和>>的区别是什么
inode节点号
md5值校验
sed扩展命令使用
vim编辑器
命令小结
mysql命令使用3
mysql命令使用2
正则表达式手册
win 10 hosts文件不生效
热门文章
安装配置tomcat
二进制方式安装mysql
lnmp源码搭建
git使用
git服务器
oracle 之 创,增,删,改操作
oracle 之 统计函数、子查询、操作符
oracle 之 连接查询
python 之 知识点(1)
oracle单行函数 之 通用函数
Copyright © 2011-2022 走看看