比如要在列表arr中查找x
def f(arr, x):
left = 0
right = len(arr)
while left < right:
mid = (left + right) //2
if mid < x:
left = mid
elif mid > x:
right = mid
else:
return mid
arr = [ i for i in range(1,100)]
print(arr)
x = 69
y = f(arr, x)
print(y)
二分法查找postgresql数据库某个表的一条tuple
# -*- coding: utf-8 -*-
import psycopg2
conn = psycopg2.connect(host="192.168.137.129", port="1921", database="postgres", user="pg10", password="postgresql@123", )
conn.autocommit=True
cur = conn.cursor()
def get_ctids():
cur.execute("SELECT ctid FROM test_toast order by ctid")
rows = cur.fetchall()
ctid_list = [eval(row[0]) for row in rows]
cur.close()
return ctid_list
def f(arr, x):
left = 0
right = len(arr)-1
while left < right:
mid = (left + right) // 2
if arr[mid] < x:
left = mid
elif arr[mid] > x:
right = mid
else:
return mid
def close_conn():
conn.close()
if __name__ == '__main__':
ctid_list = get_ctids()
x = (1199,140)
y = f(ctid_list, x)
print(y, ctid_list[y])
close_conn()