このページには最新のブラウザ(SharedArrayBuffer対応)が必要です。Chrome、Edge、Firefox、Safariを最新バージョンに更新してください。
English
What we'll do
- An algorithm is a clear list of steps that solves a problem.
- A very common job is searching: find where a value is in a list.
- We will learn two algorithms: linear search and binary search.
English
Linear search
- Check the items one by one, from start to end.
- If you find the value, return its index (position).
- If you reach the end and never find it, return
-1.
English
def linear_search(lst, target):
for i in range(len(lst)):
if lst[i] == target:
return i
return -1
print(linear_search([4, 8, 15, 16], 15))
print(linear_search([4, 8, 15, 16], 99))
English
Why a sorted list helps
- Linear search works on any list, even a messy one.
- But if the list is sorted (small to big), we can be much faster.
- Binary search uses the sorted order to skip half the list each time.
English
Binary search
- Look at the middle item.
- If it is the target, you are done.
- If the target is smaller, search the left half; if bigger, the right half. Repeat.

English
def binary_search(sorted_lst, target):
low = 0
high = len(sorted_lst) - 1
while low <= high:
mid = (low + high) // 2
if sorted_lst[mid] == target:
return mid
elif sorted_lst[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
print(binary_search([1, 3, 5, 7, 9], 7))
print(binary_search([1, 3, 5, 7, 9], 4))
English
Putting ideas together
- A search combines three building blocks you already know.
- Sequencing: do steps in order. Selection:
if/elif/else. - Iteration: a loop (
fororwhile) repeats the check.
English
In AP CSP pseudocode
- The exam writes a loop and a check like this.
FOR EACHvisits every item;IFselects;REPEAT UNTILloops until a test is true.
PROCEDURE contains(list, target)
{
FOR EACH item IN list
{
IF (item = target)
{
RETURN(true)
}
}
RETURN(false)
}
English
Common mistakes
- Binary search needs a sorted list.
- Linear search checks each item in turn.
English
Now you try
- Each task gives a procedure name and what it must return.
- Press Check answer to test your code.
探索
リストの探索
二分探索には 整列済み リストが必要ですが、線形探索より遥かに高速です。
難易度 3/5 · 200 コイン + 今日初回達成時の小ボーナス
linear_search(lst, target) を書きます。 lst 内の target の インデックス を返すか、存在しない場合は -1 を返します。アイテムを一つずつ確認します。
実行ボタンをクリックして出力を確認してください。
難易度 3/5 · 200 コイン + 今日初回達成時の小ボーナス
小さい順から大きい順に並べたリストに対して binary_search(sorted_lst, target) を書きます。 target の インデックス を返すか、存在しない場合は -1 を返します。中央を見て、毎回探索範囲を半分に切り捨てます。
実行ボタンをクリックして出力を確認してください。
難易度 3/5 · 200 コイン + 今日初回達成時の小ボーナス
target が lst に含まれるなら True を、否则 False を 返す contains(lst, target) を書きます。線形探索を再利用し、結果を -1 と比較しても構いません。
実行ボタンをクリックして出力を確認してください。