二元搜索

#include<iostream.h>

void ChoiceSort(int list[], int len);
void Swap(int&, int&);
int BinarySearch(int list[],int key, int len);
int Comp(int, int);

void main()
{
	const int SIZE=15;
	int list[SIZE]={10,15,20,30,3,
					16,18,500,21,25,
					32,56,47,56,90 };
	ChoiceSort(list, SIZE);
	cout<<"list :  ";
	for (int idx=0; idx<SIZE; idx++ )
		cout<<list[idx]<<"  ";
	cout<<endl;

	int key;
	cout<<"enter the search key : ";
	cin>>key;

	int index=BinarySearch(list, key,SIZE);
	if (index != -1)
		cout<<key<<" the index in list is :: "<<index+1<<endl;
	else
		cout << "can't found it "<<endl;

	//上面cin>>key,在输入搜索数字后的回车会被第一个cin.get()读取,当读取后就直接退出了
	//所以最好再加上一个cin.get()
	cin.get();
	cin.get();
}

void ChoiceSort(int list[], int len)
{
	int out_recy, in_recy; //min_v ;
	for(out_recy=0; out_recy<len-1;out_recy++)
	{
		//min_v=out_recy;
		for (in_recy=out_recy+1; in_recy<len; in_recy++)
		//	if (list[in_recy]<list[min_v])
		//	{
		//		min_v=in_recy;
		//	}
			if (list[out_recy]>list[in_recy])
				Swap(list[in_recy], list[out_recy]);
	}
}
int BinarySearch(int list[],int key, int len)
{
	int left=0,right=len-1,mid ;
	//int mid=(left+right)/2;
	if (key == list[0])
		return 0;
	if (key == list[len-1])
		return len-1;
	while(left<=right)
	{
		mid=(left+right)/2;
		switch( Comp(list[mid], key) )
		{
		case 2:
			right=mid-1;
			break;

		case 1:
			left=mid+1;
			break;

		case 0 :
			return mid ;
		}
		
	}
	return -1;
}
int Comp(int mid_v, int key_v)
{
	if (mid_v>key_v)
		return 2 ;
	else if (mid_v<key_v)
		return 1;
	else
		return 0 ;
}

void Swap(int& small, int& big)
{
	int temp=small;
	small=big;
	big=temp;
}

你可能感兴趣的:(搜索)