建檔日期: 2019/12/08
更新日期: None
相關軟體資訊:
Win 10 | Python 3.7.2 |
說明:所有內容歡迎引用,只需註明來源及作者,本文內容如有錯誤或用詞不當,敬請指正.
主題: 004.02 各類搜尋的演算法
搜尋演算法
搜尋演算法旨在檢查元素或從儲存它的任何資料結構中檢索元素。根據搜尋操作的型別,這些演算法通常分為兩類:
順序搜尋:在此順序搜尋列表或陣列,並檢查每個元素。例如:線性搜尋。
間隔搜尋:這些演算法是專門為搜尋排序的資料結構而設計的。這些型別的搜尋演算法比線性搜尋有效得多,因為它們反覆瞄準搜尋結構的中心並將搜尋空間分成兩半。例如:二進位制搜尋。
以下為各種演算法在一萬筆資料中搜尋一萬筆資料的索引所需時間, 以及程式碼.
結果:
0:00:09.563429 : Linear
0:00:00.400960 : Binary
0:00:00.372005 : Jump
0:00:00.273269 : Exponential
0:00:00.070810 : FibMonaccian
0:00:00.010970 : Inerpolation
程式碼:
from datetime import datetime
from math import sqrt
import random
import copy
size = 10000
data = [i for i in range(size)]
db = random.sample(range(size), size)
db_sort = copy.deepcopy(db)
db_sort.sort()
def call(func):
start_time = datetime.now()
for i in range(size):
index = func(data[i], db_sort)
print(datetime.now() - start_time,':',func.__name__)
def do_something(value):
for i in range(1000):
pass
def Binary(value, db, offset=0):
length = len(db)
index = int(length/2)
if length == 0: return None
value2 = db[index]
if value == value2:
return index + offset
elif value > value2:
return Binary(value, db[index+1:], offset=offset+index+1)
elif value < value2:
return Binary(value, db[:index], offset=offset)
def Exponential(value, db):
length = len(db)
if length == 0: return None
if value == db[0]:
return 0
i = 1
while (i<length) and (db[i]<=value):
i = i*2
index = Binary(value, db[int(i/2):min(i, length)])
if index == None: return None
return int(i/2)+index
def FibMonaccian(value, db):
length = len(db)
if length == 0: return None
f2 = 0
f1 = 1
f = f1 + f2
while f<length:
f2 = f1
f1 = f
f = f1 + f2
offset = -1
while f>1:
i = min(offset+f2, length-1)
if value > db[i]:
f = f1
f1 = f2
f2 = f - f1
offset = i
elif value < db[i]:
f = f2
f1 = f1-f2
f2 = f -f1
else:
return i
if f2 and (db[offset+1]==value): return offset+1
return None
def Inerpolation(value, db):
length = len(db)
if length == 0: return None
start = 0
stop = length-1
while (start<=stop) and (value>=db[start]) and (value<=db[stop]):
if stop==start:
if (db[start]==value): return start
return None
pos = start+int((stop-start)/(db[stop]-db[start])*(value-db[start]))
if db[pos] == value:
return pos
if db[pos] < value:
start = pos + 1
else:
stop = start - 1
return None
def Jump(value, db):
length = len(db)
if length == 0:
return None
step = old_step = int(sqrt(length))
index = 0
while db[min(step, length)-1] < value:
index = step
step += old_step
if (index >= length):
return None
while (db[index] < value):
index += 1
if (index == min(step, length)):
return None
if (db[index] == value):
return index
return None
def Linear(value, db):
if db == []: return None
index = 0
while index<size:
if value == db[index]:
return index
index += 1
return None
# This is the only one, could be called with unsorted list
call(Linear)
# All functions called should be with sorted list
call(Binary)
call(Jump)
call(Exponential)
call(FibMonaccian)
call(Inerpolation)
本作品採用《CC 協議》,轉載必須註明作者和本文連結