二分查找算法:簡(jiǎn)單的說,就是將一個(gè)數(shù)組先排序好,比如按照從小到大的順序排列好,當(dāng)給定一個(gè)數(shù)據(jù),比如target,查找target在數(shù)組中的位置時(shí),可以先找到數(shù)組中間的數(shù)array[middle]和target進(jìn)行比較,當(dāng)它比target小時(shí),那么target一定是在數(shù)組的右邊,反之,則target在數(shù)組的左邊,比如它比target小,則下次就可以只比較[middle+1, end]的數(shù),繼續(xù)使用二分法,將它一分為二,直到找到target這個(gè)數(shù)返回或者數(shù)組全部遍歷完成(target不在數(shù)組中)
優(yōu)點(diǎn):效率高,時(shí)間復(fù)雜度為O(logN);
缺點(diǎn):數(shù)據(jù)要是有序的,順序存儲(chǔ)。
python的代碼實(shí)現(xiàn)如下:
#!/usr/bin/python env# -*- coding:utf-8 -*-def half_search(array,target): low = 0 high = len(array) - 1 while low < high: mid = (low + high)/2 if array[mid] > target: high = mid - 1 elif array[mid] < target: low = mid + 1 elif array[mid] == target: print 'I find it! It is in the position of:',mid return mid else: print "please contact the coder!" return -1if __name__ == "__main__": array = [1, 2, 2, 4, 4, 5]
運(yùn)行結(jié)果如下:
I find it! It is in the position of: 44-1I find it! It is in the position of: 00-1
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選