python使用二分法實現在一個有序列表中尋找指定的元素

來源:互聯網
上載者:User

標籤:中位元   int   arch   body   指定   一半   沒有   序列   元素   

二分法是一種快速尋找的方法,時間複雜度低,邏輯簡單易懂,總的來說就是不斷的除以2除以2...

例如需要尋找有序list裡面的某個關鍵字key的位置,那麼首先確認list的中位元mid,下面分為三種情況:

如果 list[mid] < key,說明key 在中位元的 右邊;

如果 list[mid] > key,說明key 在中位元的 左邊;

如果 list[mid] = key,說明key 在中位元的中間;

範圍每次縮小一半,寫個while的死迴圈知道找到為止。

二分法尋找非常快且非常常用,但是唯一要求是要求數組是有序的

代碼如下

 

 1 #!/usr/bin/python2.7 2 # -*- coding: utf-8 -*- 3  4 def BinarySearch(lista, key): 5     # 記錄數組的最高位和最低位 6     min = 0 7     max = len(lista) - 1 8  9     if key in lista:10         # 建立一個死迴圈,直到找到key11         while True:12             # 得到中位元13             mid = (min + max) / 214             # key在數組左邊15             if lista[mid] > key:16                 max = mid - 117             # key在數組右邊18             elif lista[mid] < key:19                 min = mid + 120             # key在數組中間21             elif lista[mid] == key:22                 print str(key) + "在數組裡面的第" + str(mid) + "個位置"23                 return lista[mid]24     else:25         print("沒有該數字!")26 27 28 if __name__ == "__main__":29     arr = [1, 6, 9, 15, 26, 38, 49, 57, 63, 77, 81, 93]30     while True:31         key = input("請輸入你要尋找的數字:")32         if key == " ":33             print("謝謝使用!")34             break35         else:36             BinarySearch(lista, int(key))

 

python使用二分法實現在一個有序列表中尋找指定的元素

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.