1. 程式人生 > >python演算法9.18——插值排序

python演算法9.18——插值排序

# 對二分查詢的改進,也是對有序表進行查詢
# 基本原理:
# mid = low + (high - low) * (key - a[low]) / (a[high] - a[low])

import random
Range = 10
Length = 5
flag = 0
pos = -1

list = random.sample(range(Range),Length)
goal = random.randint(0,Range)
# list =  [0, 1, 4, 5, 7]
# goal = 10

# 氣泡排序處理
for i in range(Length-1):                   #控制迴圈次數
    for j in range(Length-i-1):             #控制每次迴圈內容
        if list[j] > list[j + 1]:
            list[j + 1], list[j] = list[j], list[j + 1]
print('search ',goal,', in list:',list)

min = 0
max = Length - 1
mid = min + int((max - min)*(goal - list[min])/(list[max] - list[min]))

if goal>list[max]:
    pass
else:
    while min<max:
        mid = min + int((max - min) * (goal - list[min]) / (list[max] - list[min]))
        if list[mid] == goal:
            flag = 1
            pos = mid
            break
        elif list[mid] > goal:
            max = mid - 1
        elif list[mid] < goal:
            min = mid + 1

if flag:
    print('find in ',pos+1,'th place')
else:
    print('not found')