Commit 0790b1c7 by BellCodeEditor

auto save

parent adaf6f8a
Showing with 48 additions and 2 deletions
'''
题目:
有一个无序的序列list_c = [
37, 99, 73, 48, 47, 40, 40, 25, 99, 51], 请先排序并打印输出。
分别尝试插入
[
20,40,41,100]到序列中合适的位置,保证其有序。
'''
list_c = [37, 99, 73, 48, 47, 40, 40, 25, 99, 51,99]
list_s = [20, 40, 41, 100]
#先排序
order_list = sorted(list_c)
print(order_list)
#浅复制,保留原来数据
ret = order_list[:]
def insert_sort(ret,num):
low = 0 #索引起点
high = len(ret) #索引终点
while low<high: # 起点索引大于或等于列表最后一个元素的索引,条件无法进入。
mid = (low+high)//2 # 取列表中间点的索引
if num<ret[mid]: # 条件判断,如果待插入列表的值小于有序列表对应mid索引的值,就向左查询
high = mid-1 # 同时确认这个中间点mid索引就是ret列表的high最高索引
else: # 如果待插入列表的值大于有序列表对应mid索引的值,就向右查询,求中点
low = mid+1 # 同时确认这个中间点mid索引就是ret列表的开始索引low的值。
return low # 这个开始索引low就是最终计算出来的待插入索引的位置low,所以返回low
for num in list_s: # 循环去取待插入列表的元素。
index = insert_sort(ret,num)# 调用上面的函数取出插入元素索引值
ret.insert(index,num) # 就地插入对应索引的值到列表ret中.
print(ret) # 打印插入元素后的列表
......@@ -6,4 +6,20 @@ for i in range(1, 101):
num = random.choice(alist)
# 请完善二分查找函数binary_search(),查找出num在列表alist里面的索引位置
def binary_search(alist,num):
\ No newline at end of file
def binary_search(alist,num):
low = 0
high = len(alist)-1
while low <= high:
mid = (low + high) // 2
guess = alist[mid]
if guess == num:
return mid
elif guess < num:
low = mid + 1
else:
high = mid - 1
return None
result = binary_search(alist,num)
print("给的数是:",num)
print("他在列表里的索引是:",result)
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment