이 페이지는 최신 브라우저(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)를 작성하십시오. target이 lst에서 첫 번째로 나타나는 인덱스를 반환하거나, 없으면 -1를 반환하십시오. 항목을 하나씩 순차적으로 확인하십시오.
출력을 보려면 '실행'을 클릭하세요.
난이도 3/5 · 200코인 + 오늘 첫 완료 시 작은 보너스 추가
작은 순서에서 큰 순서로 정렬된 리스트 binary_search(sorted_lst, target)을 작성하십시오. target의 색인을 반환하거나, 존재하지 않을 경우 -1을 반환하십시오. 중간 요소를 보고 매번 검색 범위를 절반으로 줄이십시오.
출력을 보려면 '실행'을 클릭하세요.
난이도 3/5 · 200코인 + 오늘 첫 완료 시 작은 보너스 추가
target이 lst에 포함되어 있으면 True을, 그렇지 않으면 False을 반환하는 contains(lst, target)을 작성하십시오. 선형 검색을 재사용하여 결과가 -1인지 비교할 수 있습니다.
출력을 보려면 '실행'을 클릭하세요.