3.插入排序——2路插入排序
来源:互联网 发布:网站seo分析报告 编辑:程序博客网 时间:2024/05/22 04:51
本文针对2路插入排序。
这种排序方法是对折半插入排序的改进,减少了数据移动操作的次数,但是需要另外申请比要排记录所占空间少一个记录的内存空间,从原数组中取值按大小顺序插入这个内存空间。
数据移动操作次数之所以减少是因为如果array数组中最大值和最小值出现的比较晚,那么一些稍微大或者小的值就可以直接往temp数组最上或者最下的地方插,就减少了数据移动次数;但是如果很早出现,就要移动和折半插入差不多的数据量了。
它的时间复杂度仍是O(n的平方)。
程序:
#include <stdio.h>#include <stdlib.h>#include <string.h>#define MAXSIZE 50typedef struct{int key;int other;}node;typedef struct{node array[MAXSIZE + 1];int length;}list;//2路插入排序void twoway_insertion_sort(list *l){int i,j,first,final;node *temp;temp = (node*)malloc(l->length * sizeof(node)); //存放已经排好的数据temp[0] = l->array[1];first = final = 0; //first减的地方数据是小的,final加的地方数据是大的for(i = 2;i <= l->length;++i){ //依次将l中第2个开始的数据插入到d数组if(l->array[i].key < temp[first].key){first = (first - 1 + l->length) % l->length;temp[first] = l->array[i];}else if(l->array[i].key > temp[final].key){ /* 待插记录大于d中最大值,插到d[final]之后(不需移动d数组的元素) */final = final + 1;temp[final] = l->array[i];}else{ /* 待插记录大于d中最小值,小于d中最大值,插到d的中间(需要移动d数组的元素) */j = final++; /* 移动d的尾部元素以便按序插入记录 */while(l->array[i].key < temp[j].key){temp[(j + 1) % l->length] = temp[j];j = (j - 1 + (*l).length) % l->length;}temp[j + 1]=l->array[i];}}for(i = 1;i <= l->length;i++) //从temp中将排好的数据按顺序放回ll->array[i] = temp[(i + first - 1) % l->length];}void print_array(list *l){int i;for(i = 1;i <= l->length;i++)printf("%d %d\t",l->array[i].key,l->array[i].other);printf("\n");}void main(){node data[10]={{5,6},{13,5},{22,2},{2,4},{6,5},{99,7},{6,15},{1,22},{15,12},{58,12}};list l;int i;for(i = 0;i < 10;i++)l.array[i + 1] = data[i];l.length = 10;printf("befor sort:\n");print_array(&l);twoway_insertion_sort(&l);printf("after twoway insertion sort:\n"); print_array(&l);}
结果:
[21:48:18]# ./cbefor sort:5 6 13 5 22 2 2 4 6 5 99 7 6 15 1 22 15 12 58 12after twoway insertion sort:1 22 2 4 5 6 6 5 6 15 13 5 15 12 22 2 58 12 99 7
0 0
- 3.插入排序——2路插入排序
- 插入排序—直接插入
- 插入排序--2路插入排序
- 插入排序之2路插入排序
- 插入排序——折半插入排序
- 插入排序——直接插入排序
- 插入排序——折半插入排序
- 插入排序——直接插入排序
- 插入排序——直接插入排序
- 插入排序——直接插入排序
- 插入排序——直接插入排序
- 插入排序—直接插入排序
- 插入排序(直接插入排序,折半插入排序,2路插入排序,希尔排序)
- 插入排序(直接插入排序,折半插入排序,2路插入排序,希尔排序)
- 排序2——插入,希尔排序
- 排序——插入排序
- 排序——插入排序
- 排序——插入排序
- 稀疏表达(入门)
- Unity不同平台生成中预处理的注意点
- UVa:10888 Warehouse
- JMS和ActiveMQ介绍(1)_消息传送机制
- MFC 优化窗体背景
- 3.插入排序——2路插入排序
- powerDesigner palette 工具栏不见了,怎么找回
- Codeforces 396A On Number of Decompositions into Multipliers(组合数学)
- android之res下面drawable-xxdpi说明
- POJ 1675 简单计算几何
- 英文面试题目
- C++学习之路 STL中栈,队列,优先队列
- Game Components Program Learning
- vi命令使用