普通插入排序与成对插入排序
2016-02-24 20:34
441 查看
for (int i = left, j = i; i < right; j = ++i)
{
int ai = a[i + 1];
while (ai < a[j]) {
a[j + 1] = a[j];
if (j-- == left) {
break;
}
}
a[j + 1] = ai;
}
成对插入排序,提高了插入排序的性能,同时可以插入两个数值
do {
if (left >= right) {
return;
}
} while (a[++left] >= a[left - 1]);
/*
* Every element from adjoining part plays the role
* of sentinel, therefore this allows us to avoid the
* left range check on each iteration. Moreover, we use
* the more optimized algorithm, so called pair insertion
* sort, which is faster (in the context of Quicksort)
* than traditional implementation of insertion sort.
* 具体执行过程:上面的do-while循环已经排好的最前面的数据
*(1)将要插入的数据,第一个值赋值a1,第二个值赋值a2,
*(2)然后判断a1与a2的大小,使a1要大于a2
*(3)接下来,首先是插入大的数值a1,将a1与k之前的数字一一比较,直到数值小于a1为止,把a1插入到合适的位置,注意:这里的相隔距离为2
*(4)接下来,插入小的数值a2,将a2与此时k之前的数字一一比较,直到数值小于a2为止,将a2插入到合适的位置,注意:这里的相隔距离为1
*(5)最后把最后一个没有遍历到的数据插入到合适位置
*/
for (int k = left; ++left <= right; k = ++left) {
int a1 = a[k], a2 = a[left];
if (a1 < a2) {
a2 = a1; a1 = a[left];
}
while (a1 < a[--k]) {
a[k + 2] = a[k];
}
a[++k + 1] = a1;
while (a2 < a[--k]) {
a[k + 1] = a[k];
}
a[k + 1] = a2;
}
int last = a[right];
while (last < a[--right]) {
a[right + 1] = a[right];
}
a[right + 1] = last;
}
return;
{
int ai = a[i + 1];
while (ai < a[j]) {
a[j + 1] = a[j];
if (j-- == left) {
break;
}
}
a[j + 1] = ai;
}
成对插入排序,提高了插入排序的性能,同时可以插入两个数值
do {
if (left >= right) {
return;
}
} while (a[++left] >= a[left - 1]);
/*
* Every element from adjoining part plays the role
* of sentinel, therefore this allows us to avoid the
* left range check on each iteration. Moreover, we use
* the more optimized algorithm, so called pair insertion
* sort, which is faster (in the context of Quicksort)
* than traditional implementation of insertion sort.
* 具体执行过程:上面的do-while循环已经排好的最前面的数据
*(1)将要插入的数据,第一个值赋值a1,第二个值赋值a2,
*(2)然后判断a1与a2的大小,使a1要大于a2
*(3)接下来,首先是插入大的数值a1,将a1与k之前的数字一一比较,直到数值小于a1为止,把a1插入到合适的位置,注意:这里的相隔距离为2
*(4)接下来,插入小的数值a2,将a2与此时k之前的数字一一比较,直到数值小于a2为止,将a2插入到合适的位置,注意:这里的相隔距离为1
*(5)最后把最后一个没有遍历到的数据插入到合适位置
*/
for (int k = left; ++left <= right; k = ++left) {
int a1 = a[k], a2 = a[left];
if (a1 < a2) {
a2 = a1; a1 = a[left];
}
while (a1 < a[--k]) {
a[k + 2] = a[k];
}
a[++k + 1] = a1;
while (a2 < a[--k]) {
a[k + 1] = a[k];
}
a[k + 1] = a2;
}
int last = a[right];
while (last < a[--right]) {
a[right + 1] = a[right];
}
a[right + 1] = last;
}
return;
相关文章推荐
- NOIP2015 运输计划(二分+LCA+差分)
- CODEFORCES 629 C Famil Door and Brackets
- https://projecteuler.net/problem=7
- Anaconda下import caffe出现错误TypeError: 'module' object is not callable
- hdu 1257 最少拦截系统
- 签名解密,内容验证
- 忘记电商 刘强东和京东的“如意算盘”
- Linux 下IOport编程訪问
- 2016/2/24 . html . htm . shtml 的区别
- 【转】测试思考——测试人员需要具备哪些素质?
- Java中Comparable和Comparator区别小结
- SDUT 汤圆の糖(递推算法)
- 206. Reverse Linked List
- Java类名与文件名关系
- 大型分布式网站架构技术总结
- VVDocumenter Xcode快速添加注释插件
- 算法导论第三版习题5.4
- 带标签和头部的viewpager
- String,StringBuffer,StringBuilder三者区别
- JQuery面试题答案