欧美一区二区三区,国内熟女精品熟女A片视频小说,日本av网,小鲜肉男男GAY做受XXX网站

python 排序只取前

洪振霞2年前8瀏覽0評論

Python是一門流行的編程語言,可以用它來排序并只取前N個元素來作為結果。以下是幾種Python排序方法的示例:

# 選擇排序
def selection_sort(data):
for i in range(len(data) - 1):
min_index = i
for j in range(i + 1, len(data)):
if data[j]< data[min_index]:
min_index = j
data[min_index], data[i] = data[i], data[min_index]
return data
# 快速排序
def quick_sort(data):
if len(data)<= 1:
return data
pivot = data[0]
left = [x for x in data[1:] if x< pivot]
right = [x for x in data[1:] if x >= pivot]
return quick_sort(left) + [pivot] + quick_sort(right)
# 堆排序
import heapq
def heapsort(data):
return [heapq.heappop(data) for i in range(len(data))]
data = [5, 3, 8, 4, 2]
result1 = selection_sort(data)[:3]
result2 = quick_sort(data)[:3]
result3 = heapsort(data)[:3]
print(result1) # [2, 3, 4]
print(result2) # [2, 3, 4]
print(result3) # [2, 3, 4]