zoukankan      html  css  js  c++  java
  • 二分法查找

    #include <stdio.h>
    #include <stdlib.h>
    /*数组需预先排序*/
    /*递归实现*/
    int find1( float a[], int start, int end, float tofind)
    {
    	int center = (start + end)/2;
    	if( start > end ) return -1;
    	if ( a[center] == tofind ) return center;
    	else if( a[center] > tofind )
    		find1( a, start, center-1, tofind);
    	else
    		find1( a, center+1, end, tofind);
    }
    
    /*非递归实现*/
    int find2( float a[], int start, int end, float tofind)
    {
    	while ( start <= end )
    	{
    		int center = ( start + end ) / 2;
    		if ( a[center] == tofind )
    			return center;
    		else if ( a[center] > tofind )
    			end = center - 1;
    		else
    			start = center + 1;
    	}
    	return -1;
    }
    
    int main()
    {
    	float a[10] = {0,1,2,3,4,5.5,6,7,8,9};
    	int pos;
    	pos = find2( a, 2, 9, 5.5);
    	printf("%d\n",pos);
      pos = find1( a, 2, 9, 5.5);
      printf("%d\n",pos);
    	return 0;
    }
    
  • 相关阅读:
    假期第五天
    假期第四天
    假期第三天
    假期第二天
    假期第一天
    《如何高效学习》读书笔记六
    十天冲刺-第八天
    十天冲刺第七天
    十天冲刺-第六天
    十天冲刺-第五天
  • 原文地址:https://www.cnblogs.com/zechen11/p/2191229.html
Copyright © 2011-2022 走看看