二分查找(BinarySearch) -- C++实现


// BinarySearch.h
#ifndef BINARYSEARCH_H
#define BINARYSEARCH_H

#include<iostream>
using namespace std;

#include "Component.h"

namespace jay{

	template< typename T >
	int BinarySearch(T *input,int input_len,T value )
	{
		int mid,low,high;

		low = 0;
		high = input_len - 1;
		while (low <= high)
		{
			mid = (low+high)/2;
			if (input[mid] == value)
				return mid;
			else if (input[mid] > value)
				high = mid-1;
			else
				low = mid +1;
		}

		return -1;

	}
};

#endif
//main.cpp

#include <time.h>
#include<windows.h>

#include <iostream>
#include <vector>
using namespace std;

#include "Component.h"
#include "BinarySearch.h"

using namespace jay;


int main(int argc, char* argv[])
{
	int testArray[20] = {0,1,2,3,4,5,6,7,8,9,10};

	int nIndex = BinarySearch<int>(testArray,11,15);

	cout << "查到到的索引为" << nIndex << endl;
}

 

暂无评论

注册用户登录后才能发表或者回复评论,请先登录 注册。