Binary Search
Write a binary search function to use a generic type for searching array elements. You should test the function with array of int, double and so on.
The definition of the function is given as follows.
template <typename T>
int binarySearch(T array[], T key, int arraySize);
Return the position if key is found in the array. Otherwise, return -1.
You may assume that each element only appears once in the array.
Submit the implementation of the function only.
输入格式
for every test case , an array and a key to find are given
输出格式
Return the position if key is found in the array. Otherwise, return -1.
样例输入
a={1,2,3,4,5} key = 2 a={b ,d,f,g,j,o} key = j key=z
样例输出
pos = 1 pos=4 pos=-1
提示
Think about what happens when the array is a string type ? For the binary search algorithm, please refer to http://en.wikipedia.org/wiki/Binary_search_algorithm . | ||
template <typename T> int binarySearch(T array[], T key, int arraySize) { int first = 0; int last = arraySize; while(first != last) { if(key>array[arraySize/2]) first = arraySize / 2 + 1; else if(key == array[arraySize/2]) return arraySize/2; else last = arraySize/2 - 1; } return -1; } |
SOJ.Binary Search
最新推荐文章于 2021-10-20 20:26:45 发布