分治算法--二分搜索

一.算法简介

有序表表示静态查找表时,查找函数可以用二分查找binary search or half-intervalsearch  )来实现。这种算法基于分治。https://en.wikipedia.org/wiki/Binary_search_algorithm

二.复杂度分析

二分查找的时间复杂度是O(log(n)),最坏情况下的时间复杂度是O(n)

三.算法思想及步骤

二分查找(binary search or half-interval search  )的查找过程是:先确定待查记录所在的区间,然后逐步缩小区间直到找到或找不到该记录为止。

假设 low 指向区间下界,high 指向区间上界,mid 指向区间的中间位置,则 mid  = (low + high) / 2; 

具体过程:

1.先将关键字与 mid 指向的元素比较,如果相等则返回mid。

2.关键字小于 mid 指向的元素关键字,则在 [ low, mid-1 ]区间中继续进行二分查找。 

3.关键字大于mid 指向的元素关键字,则在[ mid +1 ,high] 区间中继续进行二分查找。

伪码如下

递归Recursive

int binary_search(int A[], int key, int imin, int imax)
{
  // test if array is empty
  if (imax < imin)
    // set is empty, so return value showing not found
    return KEY_NOT_FOUND;
  else
    {
      // calculate midpoint to cut set in half
      int imid = midpoint(imin, imax);
      
      // three-way comparison
      if (A[imid] > key)
        // key is in lower subset
        return binary_search(A, key, imin, imid - 1);
      else if (A[imid] < key)
        // key is in upper subset
        return binary_search(A, key, imid + 1, imax);
      else
        // key has been found
        return imid;
    }
}

迭代Iterative

int binary_search(int A[], int key, int imin, int imax)
{
  // continue searching while [imin,imax] is not empty
  while (imax >= imin)
    {
      // calculate the midpoint for roughly equal partition
      int imid = midpoint(imin, imax);
      if(A[imid] == key)
        // key found at index imid
        return imid; 
      // determine which subarray to search
      else if (A[imid] < key)
        // change min index to search upper subarray
        imin = imid + 1;
      else         
        // change max index to search lower subarray
        imax = imid - 1;
    }
  // key was not found
  return KEY_NOT_FOUND;
}

四.C代码

#include
#include


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

int binery_search(int *a,int aim,int l,int r)
{
	int mid,low,up;
	int i;
	low=l;up=r;
	while(low<=up)
	{	
		mid=(low+up+1)/2;
		if(a[mid]==aim)
			return mid;
		else if(a[mid]>aim)
		{
			up=mid-1;
		}
		else if(a[mid]%d\taim->%d\n",item,aim);
	return  0;
}



你可能感兴趣的:(分治,二分查找,acm,算法)