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
用第二种要浪费两次复制。
查看全文
相关阅读:
权限管理命令
常用命令2
常用命令1
queue
poj 3984
L3-008 喊山 (30 分)
常州大学新生寒假训练会试 I 合成反应
dfs 的全排列
poj 1154
hdu 1241
原文地址:https://www.cnblogs.com/jjtx/p/2533471.html
最新文章
java局部变量和临时变量
深入理解java虚拟机,并发方面
深入理解java虚拟机,类加载
深入理解java虚拟机,内存管理部分
Callable与Future
java中存在垃圾回收机制,但是还会有内存泄漏的问题,原因是
volatile关键字解析
classloader 学习
arraylist和linkedlist内部的实现大致是怎样的
Java中Object的方法
热门文章
浅谈Java中的hashcode方法
String,StringBuffer与StringBuilder的区别??
javascript中对两个对象进行排序 和 java中的两个对象排序
jQuery.extend 函数详解
关机重启命令
网络命令
压缩解压命令
用户管理命令
帮助命令
文件搜索命令
Copyright © 2011-2022 走看看