Find - Find a static method (sequential search method, binary search, block search method)

First, the sequential search method

Algorithm idea:

In turn one by one compared with each keyword, if they are equal to a given value, the search is successful, the successful return value; if not equal to all keywords, the lookup fails, return a failure value. The average search length is ( n + 1 ) / 2 (n+1)/2

achieve:

int Search(int R[],int n,int k)	//	在长度为n的R[]中查找数值为k的元素
{
	int i;
	for(i=0;i<n;i++)
	{
		if(a[i]==k)
			return i;	//	查找成功返回i
	}
	return -1;	//	查找失败返回-1
}

Second, the binary search

premise:

Also known as binary search binary search, which requires linear table is ordered in.

Algorithm idea:

Compared with the look-up table in the intermediate position key, if equal to a given value, the search is successful, a successful return value; if greater than a given value, the lookup table in the left portion of the binary method; if less than the given value, the table in the right portion Find a binary method; only when the left or right of empty time lookup fails, return a failure value. The average search length is l O g 2 ( n + 1 ) 1 log_2(n+1)-1

Here Insert Picture Description
Algorithm Analysis:
Here Insert Picture Description
Implementation:

int Bsearch(int R[],int k,int low,int high)	//在R数组的low到high中查找关键字k
{
	int mid;
	while(low<=high)
	{
		mid=(low+high)/2;
		if(R[mid]==k)
			return mid;
		else if(k<R[mid])
			high=mid-1;
		else
			low=mid+1;
	}
	return -1;
}

Block search method

Algorithm idea:

Using the segment key sequence (block) orderly established segment (block) index table. With sub-index table for fast lookups. This method is called sequential index table method. Before a maximum after a key is smaller than the smallest key
, and the key is not necessarily ordered in the block. The algorithm for the process

  1. In the segment index table in the "order" or "binary" block to find where a given value;
  2. (1) determined in the block, sequentially locate a given value.

The use of the "order" lookup block, it is the average length ( b + 1 ) / 2 + ( n / b + 1 ) / 2 (b+1)/2+(n/b+1)/2
when using the "binary" lookup block, it is the average length l O g 2 ( b + 1 ) 1 + ( n / b + 1 ) / 2 log_2(b+1)-1+(n/b+1)/2
Here Insert Picture Description

Analysis of Algorithms:

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/starter_____/article/details/93750328