การค้นหา (Searching)
หน้านี้ต้องใช้เบราว์เซอร์ล่าสุด (รองรับ SharedArrayBuffer) กรุณาอัปเดต Chrome, Edge, Firefox หรือ Safari เป็นเวอร์ชันล่าสุด
English
Searching a list
- Searching means finding whether a value is in a list, and where.
- The usual answer is the index of the value, or
-1if it is missing. - Two classic methods are linear search and binary search.
English
Linear search
- Check each item in turn, from the start.
- Stop as soon as you find a match.
- It works on any list, sorted or not.
English
names = ["Sam", "Mia", "Leo"]
target = "Mia"
found = -1
for i in range(len(names)):
if names[i] == target:
found = i
break
print(found)
English
Binary search
- Binary search needs a sorted list.
- Look at the middle item. If it is the target, stop.
- If the target is smaller, search the left half; if bigger, the right half.
English
data = [2, 4, 6, 8, 10]
target = 8
low = 0
high = len(data) - 1
found = -1
while low <= high:
mid = (low + high) // 2
if data[mid] == target:
found = mid
break
elif data[mid] < target:
low = mid + 1
else:
high = mid - 1
print(found)
English
Compare them
- Linear search may check every item — slow for a long list.
- Binary search throws away half the list each step, so it is much faster.
- But binary search only works if the data is already sorted.
English
In Cambridge pseudocode
- Note
DIVis whole-number division (Python's//). - Cambridge arrays usually run from 1 to
n, the number of items.LENGTH()is for strings, so the loops usen.
// Linear search — stop at the first match
found ← -1
i ← 1
WHILE i <= n AND found = -1
IF list[i] = target THEN
found ← i
ENDIF
i ← i + 1
ENDWHILE
// Binary search (list must be sorted)
found ← -1
low ← 1
high ← n
WHILE low <= high AND found = -1
MiddleIndex ← (low + high) DIV 2
IF list[MiddleIndex] = target THEN
found ← MiddleIndex
ELSE
IF list[MiddleIndex] < target THEN
low ← MiddleIndex + 1
ELSE
high ← MiddleIndex - 1
ENDIF
ENDIF
ENDWHILE
English
Common mistakes
- Binary search needs a sorted list; it halves the range each step.
- Linear search works on any list but is slower.
English
Now you try
- Return the index of the value, or
-1when it is not found. - Press Check answer to test your code.
สำรวจ
การค้นหาเชิงเส้นเทียบกับ binary search
การค้นหาแบบทวิภาคี แบ่งครึ่ง list ในแต่ละขั้นตอน — ลดจำนวนการเปรียบเทียบอย่างมาก
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
เขียน linear_search(items, target) ที่ คืนค่า ดัชนีของ target ใน items, หรือ -1 หากไม่มีอยู่. ตรวจสอบรายการทีละตัว
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
เขียน binary_search(items, target) สำหรับ sorted list. Return ดัชนีของ target, หรือ -1 หากหายไปได้. แบ่งช่วงระยะทางครึ่งหนึ่งในแต่ละขั้นตอน
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
เขียน first_negative(items) ที่สแกน list และ คืนค่า ดัชนีของตัวเลขตัวแรกที่น้อยกว่า 0, หรือ -1 หากไม่มีเลย
คลิก Run เพื่อดูผลลัพธ์ที่นี่