题目
建立一维数组数据结构类, 对数组元素进行静态查找
主要完成如下功能:
- 实现数组数据的输入与输出
- 对数组进行顺序查找
- 对有序数组进行折半查找(递归)
- 对有序数组进行折半查找(非递归)
- 在图形类上编写一个测试该类的程序
部分代码如下
from tkinter import *
class Array(object):
"""数组"""
def __init__(self):
self.items = []
def del_array(self):
"""清空数组"""
self.items = []
def en_array(self, item):
"""数组输入"""
self.items = [int(n) for n in item.split()]
def out_array(self):
"""数组输出"""
return self.items
def search_array(self, item):
"""数组顺序查找"""
for i in range(len(self.items)):
if self.items[i] == item:
return i
return -1
def search_half(self, item):
"""折半查找非递归"""
self.items.sort() # 排序,保证列表是有序的
low = 0
height = len(self.items) - 1
while low <= height:
k = (low + height) // 2
if self.items[k] < item:
low = k + 1
elif self.items[k] > item:
height = k - 1
else:
return k # 找到后返回位置
return -1
def search_half_d(self, item, low, high):
"""折半查找递归"""
mid = (low + high) // 2
if item == self.items[mid]:
return mid + 1
elif low > high:
return -1
elif item > self.items[mid]:
return Array.search_half_d(self, item, low + 1, high)
else:
return Array.search_half_d(self, item, low, high - 1)
def windows():
def en_array():
a = inp1.get()
if a:
array.en_array(a)
txt.insert(END, " 成功保存数组 " + a)
else:
txt.insert(END, " 未输入内容 ")
inp1.delete(0, END) # 清空输入
def out_array():
b = array.out_array()
if b != -1:
txt.insert(END, " 内容如下 " + str(b))
else:
txt.insert(END, " 数组无内容 ")
def search():
a = inp1.get()
b = array.search_array(int(a))
if b != -1:
txt.insert(END, " 成功查找 位置为: " + str(b + 1))
else:
txt.insert(END, " 未能在数组找到" + a)
inp1.delete(0, END) # 清空输入
def search2():
a = inp1.get()
b = array.search_half(int(a))
if b != -1:
txt.insert(END, " 成功查找 位置为: " + str(b + 1))
else:
txt.insert(END, " 未能在数组找到" + a)
inp1.delete(0, END) # 清空输入
def search3():
a = inp1.get()
b = array.search_half_d(int(a), 0, len(array.out_array())-1)
if b != -1:
txt.insert(END, " 成功查找 位置为: " + str(b))
else:
txt.insert(END, " 未能在数组找到" + a)
inp1.delete(0, END) # 清空输入