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

    #include <iostream>
    
    using namespace std;
    
    int arr1[] = { 1,2,3,4,5,6,7,8,9 };
    int arr2[] = { 1,1,1,2,3,3,4,6,98 };
    
    int MyBinarySearch(int array[], int begin, int end, const int value)
    {
    	while (begin <= end)
    	{
    		int middle = (begin + end) / 2;
    		if (value > array[middle])
    			return MyBinarySearch(array, (middle+1), end, value);
    		else if (value < array[middle])
    			return MyBinarySearch(array, 0, (middle-1), value);
    		else
    			return middle;
    	}
    	return -1;
    }
    
    int  MyBinarySearch1(int array[], int length,const int value)
    {
    	int begin = 0;
    	int end = length - 1;
    	while (begin <= end)
    	{
    		int middle = (begin + end) / 2;
    		if (value == array[middle])
    			return middle;
    		else if (value > array[middle])
    			begin = middle + 1;
    		else
    			end = middle - 1;
    	}
    
    	return -1;
    }
    
    
    int main()
    {
    	cout << MyBinarySearch(arr1, 0, 8, 7) << endl;
    	cout << MyBinarySearch(arr2, 0, 8, 98) << endl;
    	cout << MyBinarySearch(arr1, 0, 8, 1) << endl;
    	cout << MyBinarySearch(arr2, 0, 8, 1) << endl;
    	cout << endl;
    	cout << MyBinarySearch(arr1, 0, 8, 77) << endl;
    	cout << MyBinarySearch(arr1, 0, 8, 0) << endl;
    	cout << MyBinarySearch(arr2, 0, 8, 7) << endl;
    	cout << MyBinarySearch(arr2, 0, 8, 99) << endl;
    	cout << MyBinarySearch(arr2, 0, 8, 0) << endl;
    	cout << endl;
    
    	cout << MyBinarySearch1(arr1, 9, 7) << endl;
    	cout << MyBinarySearch1(arr2, 9, 98) << endl;
    	cout << MyBinarySearch1(arr1, 9, 1) << endl;
    	cout << MyBinarySearch1(arr2, 9, 1) << endl;
    	cout << endl;
    	cout << MyBinarySearch1(arr1, 9, 77) << endl;
    	cout << MyBinarySearch1(arr1, 9, 0) << endl;
    	cout << MyBinarySearch1(arr2, 9, 7) << endl;
    	cout << MyBinarySearch1(arr2, 9, 99) << endl;
    	cout << MyBinarySearch1(arr2, 9, 0) << endl;
    	cout << endl;
    
    
        return 0;
    }
    

      

  • 相关阅读:
    Atitit 编程语言原理与概论attilax总结
    Atitit.attilax软件研发与项目管理之道
    Atitit.研发团队与公司绩效管理的原理概论的attilax总结
    Atitit.软件兼容性原理与实践 v3 q326.docx
    Atitit.html css  浏览器原理理论概论导论attilax总结
    atitit.http原理与概论attilax总结
    Atitit.并发编程原理与概论 attilax总结
    Atitit selenium3 新特性
    asp.net里获取当前时间,并字符串格式化转换(转)
    软件设计师
  • 原文地址:https://www.cnblogs.com/itdef/p/6097955.html
Copyright © 2011-2022 走看看