二分搜索(Binary Search)
当我们在字典中查找某个单的时候,一般我们会翻到一个大致的位置(假设吧,翻到中间位置),开始查找。如果翻到的正好有我们要的词,那运气好,查找结束。如果我们要找的词还在这个位置的前面,那我们对前面的这一半词典继续搜索,翻到某个位置(假设是四分之一的位置)等等。这个二分搜索的工作原理一样。相应的算法就叫做二进制搜索算法。
迭代版本算法:
//iterative binary search which returns index of element int binarySearchIterative(int arr[], int size, int data) { int low = 0; int high = size-1; int mid; while(low<=high) { mid = low + (high-low)/2; //To avoid overflow by (low + high) if(arr[mid] == data) return mid; else { if(arr[mid] < data) low = mid + 1; // search in right half else high = mid - 1; // search in left half } } return -1; }
递归版本算法:
//recursive binary search which returns index of element int binarySearchRecursive(int arr[], int low, int high, int data) { if(low<=high) { int mid = low + (high-low)/2; // To avoid overflow if(arr[mid] == data) return mid; else { if(arr[mid] < data) //search in right half. return binarySearchRecursive(arr, mid+1, high, data); else //search in left half. return binarySearchRecursive(arr, low, mid-1, data); } } return -1; }
Copyright © 2015 programnote