插入排序程序有问题,求指导~~
时间:2011-10-23
来源:互联网
下面是我写得插入排序的代码,我在查找插入位置时,采用的是二分查找法,但是运行出现程序终止的问题。不知道错在哪儿了~~求大虾指导~~
C/C++ code
C/C++ code
//insertion sort #include <iostream> using namespace std; //在数组a[low]---a[high]查找val插入的位置 int InsertLoc(int *a,int low,int high,int val) { if(low == high) { if(val > *(a + low))return (low + 1); else return low; } int mid = (low + high) / 2; if(val > *(a + mid) && val < *(a + mid + 1)) return mid; else if(val < *(a + mid) && val < *(a + mid + 1)) return InsertLoc(a,low,mid,val); else return InsertLoc(a,mid,high,val); } //改进:用二分查找来找到插入的位置 void InsertionSort(int *a,int n) { int temp,insert_location; for(int i = 1;i < n;++i) { temp = *(a + i); int j = i - 1; insert_location = InsertLoc(a,0,j,temp); cout<<"insert_location:"<<insert_location<<endl; while(j >= insert_location) { *(a + j + 1) = *(a + j); --j; } *(a + insert_location) = temp; } } int main() { int n,temp; cout<<"please input the number of the values that need to sort:"<<endl; cin>>n; int *a = (int*)malloc(n * sizeof(int)); cout<<"please input each value:"<<endl; for(int i = 0;i < n;++i) { cin>>temp; *(a + i) = temp; } InsertionSort(a,n); cout<<"the values after sort:"<<endl; for(int i = 0;i < n;++i) cout<<*(a + i)<<" "; }
作者: xiajun07061225 发布时间: 2011-10-23
二分查找函数有问题,修改如下:
C/C++ code
C/C++ code
int InsertLoc(int *a,int low,int high,int val) { if(low == high) { if(val > *(a + low))return (low + 1); else return low; } int mid = (low + high) / 2; if(val > *(a + mid)) return InsertLoc(a,mid+1,high,val); else if(val < *(a + mid)) return InsertLoc(a,low,mid-1,val); else return mid; }
作者: pb_myown 发布时间: 2011-10-23
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28