# Python数据结构——查找和排序

164人阅读 评论(0)

1.1线性查找

if key in theArray :
print( "key在 array中." )
else :
print( "key 不在 array中." )

def linearSearch( theValues, target ):
n = len( theValues )
for i in range( n ) :
#如果欲查找的元素存在于列表中，返回Ture
if theValues[i] == target
return True
return False    #如果没找到，返回False

 def sortedLinearSearch( theValues, item ) :
n = len( theValues )
for i in range( n ) :
# 如果欲查找的元素存在于列表中，返回Ture
if theValues[i] == item :
return True
# 如果欲查找的元素大于当前元素, 则不在序列中.
elif theValues[i] > item :
return False

return False # 元素不在序列中.

 def findSmallest( theValues ):
n = len( theValues )
# 假设序列中第一个元素时最小.
smallest = theValues[0]
# 查看序列中其他更小的元素.
for i in range( 1, n ) :
if theList[i] < smallest :
smallest = theValues[i]

return smallest # 返回最小值.


1.2、二分查找

 def binarySearch( theValues, target ) :
low = 0
high = len(theValues) - 1
#重复使用二分法知道找到元素
while low <= high :
# 确定序列中间值.
mid = (high + low) // 2
# 中间值是目标元素么?
if theValues[mid] == target :
return True
# 目标元素小于中间值?
elif target < theValues[mid] :
high = mid - 1
# 目标元素在中间值后面?
else :
low = mid + 1

# 如果序列不能再分，则结束.
return False

2、排序

.

def bubbleSort( theSeq ):
n = len( theSeq )
# Perform n-1 bubble operations on the sequence
for i in range( n - 1 ) :
# Bubble the largest item to the end.
for j in range( i + n - 1 ) :
if theSeq[j] > theSeq[j + 1] : # swap the j and j+1 items.
tmp = theSeq[j]
theSeq[j] = theSeq[j + 1]
theSeq[j + 1] = tmp

.

def selectionSort( theSeq ):
n = len( theSeq )
for i in range( n - 1 ):
# Assume the ith element is the smallest.
smallNdx = i
# Determine if any other element contains a smaller value.
for j in range( i + 1, n ):
if theSeq[j] < theSeq[smallNdx] :
smallNdx = j

# Swap the ith value and smallNdx value only if the smallest value is
# not already in its proper position. Some implementations omit testing
# the condition and always swap the two values.
if smallNdx != i :
tmp = theSeq[i]
theSeq[i] = theSeq[smallNdx]
theSeq[smallNdx] = tmp

def insertionSort( theSeq ):
n = len( theSeq )
# Starts with the first item as the only sorted entry.
for i in range( 1, n ) :
# Save the value to be positioned.
value = theSeq[i]
# Find the position where value fits in the ordered part of the list.
pos = i
while pos > 0 and value < theSeq[pos - 1] :
# Shift the items to the right during the search.
theSeq[pos] = theSeq[pos - 1]
pos -= 1

# Put the saved value into the open slot.
theSeq[pos] = value

3、有序列表

1
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：8521次
• 积分：351
• 等级：
• 排名：千里之外
• 原创：13篇
• 转载：5篇
• 译文：14篇
• 评论：3条
评论排行