// Bsearch. CPP: defines the entry point for the console application. // # include "stdafx. H "# include <iostream> using namespace STD; Template <class T> void printfnum (t a [], const Int & N ); /*** search N in a [], return the index, if not find, return-1. */template <class T> int bsearch (t a [], const Int & length, const Int & N) {int left = 0, Right = length-1; while (left <= right) {int middle = (left + right)/2; // Cout <"middle:" <middle <", left:" <left <", right:" <right <Endl; if (n <A [Middle]) {right = middle-1;} else if (n> A [Middle]) {left = middle + 1 ;} else {return middle;} return-1;}/*** a better one * search N in a [], return the index, if not find, return-1. */template <class T> int betterbsearch (t a [], const Int & length, const Int & N) {int left =-1, Right = length-1; while (left + 1! = Right) {// left <Right & A [left] <n <= A [right] int middle = (left + right)/2; if (A [Middle] <n) {// A [left] <nleft = middle;} else {// A [right] >= nright = middle ;}} if (Right> = length | A [right]! = N) // No findreturn-1; return right;}/*** test function */bool testbsearch () {const int num = 20; int beginnum = 10; int T [num]; for (INT I = 0; I <num; ++ I) {T [I] = beginnum; ++ beginnum;} bool result = true; for (Int J = 0; j <num; ++ J) {If (bsearch (T, num, t [J])! = J) {result = false ;}// test no findif (bsearch (T, num, t [0]-1 )! =-1 | bsearch (T, num, t [NUM-1] + 1 )! =-1) {result = false;} return result;}/*** test function */bool testbetterbsearch () {const int num = 20; int beginnum = 10; int T [num]; for (INT I = 0; I <num; ++ I) {T [I] = beginnum; ++ beginnum;} bool result = true; for (Int J = 0; j <num; ++ J) {If (betterbsearch (T, num, t [J])! = J) {result = false ;}// test no findif (betterbsearch (T, num, t [0]-1 )! =-1 | betterbsearch (T, num, t [NUM-1] + 1 )! =-1) {result = false;} return result;} int main (INT argc, char * argv []) {const int num = 10; int T [num] = {10, 11, 12, 13, 14, 15, 16, 17, 18, 20}; printfnum (T, num); For (INT I = 0; I <num; ++ I) {cout <t [I] <"was at index:" <bsearch (T, num, t [I]) <Endl ;} cout <"searching 100 in array T, Result:" <bsearch (T, num, 100) <Endl; cout <"bsearch Test Result: "<testbsearch () <Endl; cout <" betterbsearch Test Result: "<testbetterbsearch () <Endl; return 0 ;} template <class T> void printfnum (t a [], const Int & N) {for (INT I = 0; I <n; ++ I) {cout <A [I] <"," ;}cout <Endl ;}
Http://www.waitingfy.com /? P = 464