二分查詢c++程式碼
阿新 • • 發佈:2019-02-05
#include <iostream>
using namespace std;
/*
*二分查詢思想:1、陣列從小到大排序;2、查詢的key每次和中間數比較,如果key小於mid
查詢mid左側的陣列部分;如果key大於mid,則查詢mid右側的陣列部分;如果相等,則直接返回mid。
輸入:排序陣列-array,陣列大小-aSize,查詢值-key
返回:返回陣列中的相應位置,否則返回-1
*/
//非遞迴查詢
int BinarySearch(int *array, int aSize, int key)
{
if ( array == NULL || aSize == 0 )
return -1;
int low = 0;
int high = aSize - 1;
int mid = 0;
while ( low <= high )
{
mid = (low + high )/2;
if ( array[mid] < key)
low = mid + 1;
else if ( array[mid] > key )
high = mid - 1;
else
return mid;
}
return -1;
}
//遞迴
int BinarySearchRecursive(int *array, int low, int high, int key)
{
if ( low > high )
return -1;
int mid = ( low + high )/2;
if ( array[mid] == key )
return mid;
else if ( array[mid] < key )
return BinarySearchRecursive(array , mid+1, high, key);
else
return BinarySearchRecursive(array, low, mid-1, key);
}
int main()
{
int array[10];
for (int i=0; i<10; i++)
array[i] = i;
cout<<"No recursive:"<<endl;
cout<<"position:"<<BinarySearch(array, 10, 6)<<endl;
cout<<"recursive:"<<endl;
cout<<"position:"<<BinarySearchRecursive(array, 0, 9, 6)<<endl;
return 0;
}