关于折半插入排序
本人新学vc,编译环境为vc2005express,想写一个数组折半插入排序的程序,在多方借鉴下程序如下:
// array_4.cpp : Defines the entry point for the console application.
//binaryInsertSort
#include "stdafx.h "
#include <iostream>
using namespace std;
const int num=16;
int main(int argc, _TCHAR* argv[])
{
int a[num]={9,8,7,6,5,4,3,2,11,12,13,16,15,14,19,1};
int left,right,middle,tempRecord;
for(int i=1;i <num;i++)
{
tempRecord=a[i];//将当前待插入记录保存在临时变量中
left=0;
right=num-1;//记录已排好序序列的左右位置
while(left <=right)//开始查找待插入记录的正确位置
{
middle=(left+right)/2;//记录中间位置
if(tempRecord <a[middle])//如果待插入记录比中间记录小,就在左一半中查找,否则,在右一半中查找
right=middle-1;
else
left=middle+1;
}
//将前面所有大于当前待插入记录的记录后移
for(int j=i-1;j> =left;j--)
a[j+1]=a[j];
a[left]=tempRecord;//将待插入记录回填到正确位置.
}
for(int i=0;i <=num-1;i++)
cout < <a[i] < < " ";
cout < <endl;
return 0;
}
编译通过后会产生错误如下:
Debug Error!
Program:...
Module:...cuments\....
File:
Run-Time Check Failure #2 - Stack around the variable ' a ' was corruptred.
(Press Retry to debug the application)
然后修改了数组声明改为static int a[num]={9,8,7,6,5,4,3,2,11,12,13,16,15,14,19,1};
然后就没有debug error了,可是还是不能正确排序,希望众位大人不吝赐教.
[解决办法]
我看明白了 是这么个意思
你的 right=num-1;
改成 i-1;