python實現順序查詢和折半查詢

2021-08-03 06:58:54 字數 2566 閱讀 1639

1 順序查詢

特點:不需要內容有序,乙個乙個查詢

缺點:查詢效率低,不適合大資料 ,假設資料的總個數為n,則計算複雜度為n/2

下面的程式由三個函式組成,第乙個函式是裝飾器,作用是計算函式的

執行時間

第二個函式的作用是資料的輸入,為方便直接給列表裝載i

第三個函式的作用是實現順序查詢

# -*- coding: utf-8 -*-

"""spyder editor

this is a temporary script file.

"""import time

list_num=

#裝飾器,計算函式的執行時間

def timer(func):

start_time=time.time()#獲取函式執行前的系統時間

func(*args,**kwargs)

stop_time=time.time()#獲取函式執行後的系統時間

print(start_time)

print(stop_time)

print('the func run time is %f'%(stop_time-start_time))

return 0

#輸入資料

def datain_func(n):

for i in range(n):

#data_in=int(input('請輸入資料:'))

#print('輸入資料列表:')

#print(list_num)

#查詢@timer#等價於 search_func=timer(search_func)

def search_func(s):

cnt=0

for i in list_num:

cnt+=1

if i==s:

print('你要找的數在第%d位置'%cnt)

return i

print('你要查詢的數不再這個檔案裡')

#資料輸入

data_num=int(input('請輸入要資料的個數:'))

datain_func(data_num)

#資料查詢

search=int(input('請輸入要查詢的數:'))

search_func(search)

2 折半查詢

特點:要求資料是有序的如【0,1,2,3,4,5,6,7,8,9】

優點:效率高

缺點:要求資料有序

參考**的函式功能與上類似直接貼出

# -*- coding: utf-8 -*-

"""created on sat jul 1 19:08:42 2017

@author: wzqya

"""import time

#裝飾器

def timer(func):

start_time=time.time()

func(*args,**kwargs)

stop_time=time.time()

print(start_time)

print(stop_time)

print('程式執行時間為%f'%(stop_time-start_time))

return 0

list_num=

#資料輸入

def data_in_func(n):

for i in range(n):

#資料查詢

@timer

def search_func(search):

low=0

high=num-1

while low<=high:

mid=(low+high)//2

if list_num[mid]==search:

print('要查詢的數的第%d處'%(mid+1))

return 0

elif list_num[mid]>search:

high=mid-1

else:

low=mid+1

else:

print('未找到。。。。。')

num=int(input('num='))

data_in_func(num)

search=int(input('search='))

search_func(search)

結果比對

順序查詢:

請輸入要資料的個數:100000000

請輸入要查詢的數:99999999999

你要查詢的數不再這個檔案裡

1498908344.769997

1498908352.447436

the func run time is 7.677439

折半查詢:

num=100000000

search=9999999999

未找到。。。。。

1498908393.8948069

1498908393.8958068

程式執行時間為0.001000

很明顯折半查詢的效率高多了

順序查詢和折半查詢

順序查詢可以是線性表也可以是鍊錶,同是既可以是有序的也可以是無序。折半查詢僅適用於有序的線性表 include include define elemtype inttypedef struct sstable 表的資料結構 void creatss sstable st 建立線性表 void pr...

順序表的順序查詢和折半查詢

順序查詢 include using namespace std intseqsearch int r,int n,int k return i int main int k cout 請輸入要查詢的數 k for int i 1 i n i cout 該數在陣列中的位置為 cout seqsear...

靜態查詢(順序查詢和折半查詢)

聽說過一句話,程式設計之久,除了資料結構和演算法什麼也不屬於我們。為了更好的學習資料結構和演算法,今天決定先把清華大學出版的資料結構 c語言版 書中的演算法實現一遍。現在開始第一彈。貴在堅持。順序查詢 演算法描述 include include 順序表的查詢 define eq a,b a b de...