# 黑马程序员-IOS学习笔记 折半查找 在数组中插入一个数返回index

------Java培训、Android培训、iOS培训、.Net培训、期待与您交流！-------

/*

折半查找

@param len 数组长度

@param key 要查找的数

@return 要查找的数的位置,如果找不到返回-1

*/

int searchItem(int arr[],int len,int key){

//先定义变量

int low = 0,high = len-1,mid;

//循环

while (low<=high) {

//计算mid的位置

mid = (low+high)/2;

//判断key a[mid]

if(key>arr[mid]){

//key>a[mid]    low = mid+1;

low = mid+1;

}else if(key<arr[mid]){

//key<a[mid]    high = mid-1；

high = mid - 1;

}else{

//key==a[mid]   return min;

return mid;

}

}

//下面是查找不到的情况

return -1;

}

/*

折半查找

插入一个数 返回index

*/

int insertItem(int arr[],int len,int key){

//先定义变量

int low = 0,high = len-1,mid;

//循环

while (low<=high) {

//计算mid的位置

mid = (low+high)/2;

//判断key a[mid]

if(key>arr[mid]){

//key>a[mid]    low = mid+1;

low = mid+1;

}else if(key<arr[mid]){

//key<a[mid]    high = mid-1；

high = mid - 1;

}else{

//key==a[mid]   return min;

return mid + 1;

}

}

//下面是查找不到的情况

return low;

}


07-09 278

09-28 661

06-15 402

09-01 1.1万

11-11 1038

09-07 990

09-01 9650

03-28 150

03-08 470

11-29 1.8万