線性搜尋Linear Search
從列表開首逐項比較,直到找到目標或到達最後一項。它可用於未排序列表,設計簡單,但列表愈長,最壞情況愈慢。
Compare items from the beginning until the target is found or the last item is reached. It works on unsorted lists and is simple, but the worst case grows with list length.
79508564978880
target = int(input())
found = False
i = 0
while i < len(mark) and found == False:
if target == mark[i]:
found = True
i = i + 1
print(found)
二分搜尋Binary Search
只適用於已排序列表。每次比較中間項目,然後捨棄不可能包含目標的一半搜尋範圍。
Only works on sorted lists. Each comparison checks the middle item, then discards the half of the search range that cannot contain the target.
50516465757980858897
start = 0
end = len(mark) - 1
found = False
while start <= end and found == False:
mid = int((start + end) / 2)
if mark[mid] == target:
found = True
elif target < mark[mid]:
end = mid - 1
else:
start = mid + 1
選擇排序Selection Sort
在未排序部分找出最大或最小值,與未排序部分第一項交換,重複直到完成。
Find the maximum or minimum in the unsorted part, swap it with the first unsorted item, and repeat.
for i in range(0, len(mark)):
max_index = i
for j in range(i+1, len(mark)):
if mark[j] > mark[max_index]:
max_index = j
mark[i], mark[max_index] = mark[max_index], mark[i]
插入排序Insertion Sort
把列表分成已排序和未排序部分,取出未排序部分第一項作 key value,插入已排序部分的正確位置。
Divide the list into sorted and unsorted parts, take the first unsorted item as the key value, and insert it into the correct sorted position.
for i in range(1, len(mark)):
key = mark[i]
j = i - 1
while j >= 0 and key > mark[j]:
mark[j+1] = mark[j]
j = j - 1
mark[j+1] = key
冒泡排序Bubble Sort
逐對比較相鄰項目,若順序錯誤便交換。一輪完成後,最小或最大項目會移到已排序區。
Compare adjacent items and swap if they are in the wrong order. After each pass, one smallest or largest item moves into the sorted part.
for i in range(0, len(mark)-1):
for j in range(0, len(mark)-1-i):
if mark[j] < mark[j+1]:
mark[j], mark[j+1] = mark[j+1], mark[j]
合併排序與快速排序Merge Sort and Quick Sort
兩者都使用分治和遞迴。合併排序把列表分到每個子列表只剩一項,再合併成有序列表;快速排序選 pivot,把較小和較大項目分到兩邊再遞迴處理。
Both use divide-and-conquer and recursion. Merge sort divides until sub-lists contain one item, then merges sorted lists. Quick sort chooses a pivot, partitions smaller and larger items, then recurses.
1
Divide
把大問題分成子問題。Split a large problem into smaller ones.
2
Conquer
在子列表中排序或分割。Sort or partition sub-lists.
3
Combine
把結果合併成完整有序列表。Combine results into a fully sorted list.