折半查找插入排序算法
2015-11-01 22:59
218 查看
时间复杂度 :θ(n²)
附加存储空间:一个存储单元
稳定性:稳定
原址性:是
特点:是对直接插入排序算法的一种改进,通过折半查找,减少了比较次数,移动次数没变。
与直接插入排序的比较:当数据量越大,原始的排序越凌乱,特别是排序前后单个元素次序变化巨大时,折半插入排序快;否则,直接插入排序快
C#
附加存储空间:一个存储单元
稳定性:稳定
原址性:是
特点:是对直接插入排序算法的一种改进,通过折半查找,减少了比较次数,移动次数没变。
与直接插入排序的比较:当数据量越大,原始的排序越凌乱,特别是排序前后单个元素次序变化巨大时,折半插入排序快;否则,直接插入排序快
#include <iostream> using namespace std; struct RecType { int key; string data; }; void BinInsertSort(RecType *p,int length) { for (int i =2;i <length;i ++) { p[0]=p [i ]; //暂存 int low=1; int high=i -1; while (low <=high) //折半查找 { int mid=(low+high)/2; if (p[0].key<p[mid].key) { high=mid-1; } else //关键字相同时,插入到高半区,保证算法的稳定性 { low=mid+1; } } for (int j=i -1;j >=high+1;j --) //移动记录 { p [j +1]=p [j ]; } p[high+1]=p[0]; //插入 } } int main() { int b; RecType R[8]; for (int i=1;i <8;i ++) { cin>>R [i ].key; } BinInsertSort(R ,8); for (int i=1;i <8;i ++) { cout<<R [i ].key<<endl; } cin>>b; return 0; }
C#
public struct RecType //数据节点类型 { public int Key; public string data; } public class BinInsertSort { public const int MaxSize=100; public RecType[] R; public int Length; public BinInsertSort() //初始化 { R = new RecType[MaxSize]; Length = 0; } public void Input() //输入数据 { Console.WriteLine("Please input some Integers:"); string e = Console.ReadLine(); string[] f = e.Split(new char[] { ',' }); for (int i = 0; i < f.Length; i++) { R[i].Key = Convert.ToInt32(f[i]); } Length = f.Length; } public void BinInsertSort1() //二分插入排序 { int i, j, low, high, mid; RecType tmp; for (i = 1; i < Length; i++) { tmp = R[i]; low = 0; high = i - 1; while (low <= high) { mid = (low + high) / 2; if (tmp.Key < R[mid].Key) high = mid - 1; else low = mid + 1; } for (j = i - 1; j >= high + 1; j--) { R[j + 1] = R[j]; } R[high + 1] = tmp; } } public void Display() //显示数据 { for (int i = 0; i < Length; i++) { Console.Write(R[i].Key+" "); } Console.ReadKey(); } } <pre name="code" class="csharp"> static void Main(string[] args) { BinInsertSort L = new BinInsertSort(); L.Input(); L.BinInsertSort1(); L.Display(); }
相关文章推荐
- linux标准输入输出错误输出
- 11月,我的生活计划
- Makefile自动生成头文件依赖
- 模板栈的实现
- 由WEBX5自动生成的代码对JS中prototype的研究
- linux RHEL6 中md0重启后变为 md127的解决办法
- 正确的慢跑姿势是怎样的?
- SpringMVC拦截器(资源和权限管理)
- 曝光补偿
- 控制器之间的传值—— segue与代理的合作
- 顺便再写一个递归 复习一下前面学的知识
- Sudoku - The 2015 China Collegiate Programming Contest && UESTC 1222
- java Servlet接口及应用
- hdu5119 DP
- 深入分析js中的constructor 和prototype
- Miscalculation(模拟题)
- 25 1000-digit Fibonacci number - Project Euler
- 备份恢复八大核心
- 通过NSNotification来监听键盘弹出和弹回
- RAID学习笔记