二分检索,顺序检索模板

#include <stdlib.h>
#include <iostream>
using namespace std;

int cmp(const void *a, const void *b)
{
	return ( *(int *)a - *(int *)b );
}

int binary_search( int *a, int n, int key )			//二份检索
{
	qsort(a, n, sizeof(a[0]), cmp);
	int mid, front=0, back=n-1;
	while (front<=back)
	{
		mid = (front+back)/2;
		if (a[mid]==key)
			return mid;
		if (a[mid]<key)
			front = mid+1;
		else back = mid-1;
	}
	return -1;						//没有返回-1;
}

int Sequential_search(int a[], int n, int key)			//顺序检索
{
	for(int i=0; i<n; i++)
		if(a[i] == key)	return i;
	return -1;
}





附件列表

     

    posted @   sober_reflection  阅读(146)  评论(0编辑  收藏  举报
    努力加载评论中...
    点击右上角即可分享
    微信分享提示