/**
* +|------------------------------------------------------|+
* 用LPC实现二分查找算法
* 二分查找是一个分治算法的一个特例,需要要找寻的源数据已经是一个
* 按照顺序排列的对应数组(个数m),这样查找,如果m/2的数据不等于c,
* 按照排序的类型查找另外一半。
* +|------------------------------------------------------|+
*/
/*
sorttype:0 表示升序排列;1 表示降序排列;
*/
void _BinarySearch(mixed array arrSort, mixed c, int sorttype, int start,mapping mindex)
{
int arrNum; //数组个数
mixed array arrHalf; //剩下一半的数组
int halfNum;
int i;
arrNum = sizeof(arrSort);
//先判断剩下的两个
if (arrNum == 2) {
if(arrSort[0] == c){
mindex["index"]=start+0;
return;
} else if(arrSort[1] == c){
mindex["index"]=start+1;
return;
} else {
mindex["index"]=-1;
return;
}
} else if (arrNum == 1) {
if(arrSort[0] == c){
mindex["index"]=start+0;
return;
} else {
mindex["index"]=-1;
return;
}
}
if (arrNum%2!=0) {
halfNum = arrNum/2-1;
if(arrSort[arrNum/2] == c) {
mindex["index"]=arrNum/2+start;
return;
}
if ((arrSort[arrNum/2] < c && sorttype==1) || (arrSort[arrNum/2] > c && sorttype==0)) { //前半段
arrHalf = allocate(arrNum/2);
for(i=0;i<=halfNum;i++) {
arrHalf[i] = arrSort[i];
}
mindex["time"] = mindex["time"]+1;
_BinarySearch(arrHalf, c, sorttype, start,mindex);
//return -1;
} else {
arrHalf = allocate(arrNum/2);
for(i=arrNum/2+1;i<arrNum;i++) {
arrHalf[i-arrNum/2-1] = arrSort[i];
}
mindex["time"] = mindex["time"]+1;
_BinarySearch(arrHalf, c, sorttype, start+arrNum/2+1,mindex);
//return -1;
}
} else {
halfNum = arrNum/2;
if (arrSort[halfNum-1] == c) {
mindex["index"]=start+halfNum-1;
return;
}
if (arrSort[halfNum] == c) {
mindex["index"]= start+halfNum;
return;
}
if ((arrSort[halfNum-1] < c && sorttype==1) || (arrSort[halfNum-1] > c && sorttype==0)) { //前半段
arrHalf = allocate(halfNum);
for(i=0;i<halfNum;i++) {
arrHalf[i] = arrSort[i];
}
mindex["time"] = mindex["time"]+1;
_BinarySearch(arrHalf, c, sorttype, start,mindex);
//return -1;
} else {
arrHalf = allocate(halfNum);
for(i=halfNum;i<arrNum;i++) {
arrHalf[i-halfNum] = arrSort[i];
}
mindex["time"] = mindex["time"]+1;
_BinarySearch(arrHalf, c, sorttype, start+halfNum,mindex);
//return -1;
}
}
}
void main(int num,int c)
{
mixed array arrSort;
int i;
mapping mindex=([
"index":-1,
"time" : 0,
]);
message("system",sprintf("start:%d/n",time()),users());
arrSort=allocate(num);
for(i=0;i<num;i++) {
arrSort[i] = i+1;
}
_BinarySearch(arrSort,c,0,0,mindex);
message("system",sprintf("end:%d/n",time()),users());
message("system",sprintf("下标:%d/t执行的次数:%d/n",mindex["index"],mindex["time"]),users());
}
执行结果:
call bsearch.c->main(10000,517)
start:1151380996
end:1151380996
下标:516 执行的次数:12