Algorithms: Searching, Efficiency and Limits

AP Computer Science Principles · Unit 3 — Algorithms and Programming

Linear search and binary search

Every algorithm can be built from three structures: sequencing, selection and iteration. Different algorithms can solve the same problem, and algorithms that look different can be equivalent; the exam asks you to compare them by correctness and by efficiency.

Linear (sequential) search checks each element in order until the target is found or the list ends. It works on any list, sorted or not. In the worst case — the target is last or absent — it examines all $n$ elements.

Binary search works only on a sorted list. It compares the target with the middle element of the part still under consideration; if they are equal it stops, otherwise it throws away the half that cannot contain the target and repeats on the other half. Because each comparison eliminates about half of the remaining elements, the worst case uses only about $\log_2 n$ comparisons: at most $k$ comparisons can search a list of up to $2^k-1$ elements. A list of 1,000 elements needs at most 10 comparisons, since $2^{10}-1=1023 \ge 1000$; a list of 500 needs at most 9, since $2^9-1=511$. Linear search on the same lists would need up to 1,000 and 500.

Binary search is often more efficient than linear search on a sorted list, but it is not free: if the data are unsorted and searched only once, sorting first can cost more than a single linear search. And on an unsorted list binary search can simply give the wrong answer, because discarding a half is only safe when order guarantees the target is not there.

31821231542152663073484194710521158126313701477153812152126303441475258637077lượt 1: low = 1, high = 15, mid = 8 → 34 < 58 nên bỏ nửa trái, low = 9lượt 2: low = 9, high = 15, mid = 12 → 58 = 58, tìm thấy sau 2 lần sotìm số 5 (không có): mid lần lượt 8, 4, 2, 1 rồi low > high — 4 lần so15 phần tử: tối đa 4 lần so, vì mỗi lần so loại một nửa phần còn lại
Tìm kiếm nhị phân trên 15 phần tử. Ô đậm là phần tử giữa được so ở mỗi lượt; ô mờ đã bị loại. Mỗi lượt loại một nửa, nên dù tìm thấy hay không, không bao giờ quá 4 lần so với 15 phần tử.

Reasonable time, heuristics and undecidable problems

Efficiency is an estimate of the computational resources — usually time, measured as the number of steps — an algorithm uses as a function of the input size $n$. It is judged informally by how the step count grows, often found by counting how many times a loop body runs. Algorithms whose step count grows like a polynomial in $n$ ($n$, $n^2$, $n^3$, $n\log n$) are said to run in a reasonable amount of time. Algorithms whose step count grows exponentially ($2^n$) or factorially ($n!$) run in an unreasonable amount of time: adding just one more item doubles the work for $2^n$, and with $n=60$ cities, checking every possible route is beyond any computer.

Some problems are naturally phrased as decision problems (a yes/no answer: is there a route shorter than 500 km?) and some as optimization problems (find the shortest route). When the only known exact algorithms are unreasonable, programmers use a heuristic: an approach that produces a solution that is not guaranteed to be optimal but is found in reasonable time — for example, always driving to the nearest unvisited city. Heuristics are used precisely when finding the best answer is impractical.

Some problems cannot be solved by any algorithm at all. A decidable problem is a decision problem for which an algorithm can be written that gives a correct yes/no answer for every possible input. An undecidable problem is one for which no such algorithm can exist; the classic example is the halting problem, deciding for every program and input whether the program eventually stops. Undecidable does not mean "hard" or "slow": it means impossible for all inputs, even with unlimited time. It also does not mean every instance is unsolvable — some particular instances may be decided, just never all of them by one algorithm.

Worked example: Đếm số lần so và chọn cách tiếp cận

(1) A sorted list has 1,000,000 elements. Find the maximum number of comparisons for binary search and for linear search. (2) A delivery company must visit 40 addresses each morning and wants the shortest route. Its programmer says, “Checking every order of the 40 addresses guarantees the best route, so we should do that.” Evaluate this plan.

Solution

(1) Tìm $k$ nhỏ nhất với $2^k-1 \ge 1{,}000{,}000$: $2^{19}-1=524{,}287$ chưa đủ, $2^{20}-1=1{,}048{,}575$ đủ. Tìm nhị phân cần tối đa 20 lần so; tìm tuần tự cần tối đa 1.000.000 lần.

(2) Số thứ tự đi qua 40 địa chỉ là $40!$, khoảng $8 \times 10^{47}$ — số bước tăng theo giai thừa, thời gian không hợp lý: không máy nào thử hết kịp trước buổi sáng, kể cả trong hàng tỉ năm. Kế hoạch đúng về lý thuyết nhưng không khả thi. Nên dùng một heuristic, ví dụ luôn tới địa chỉ gần nhất chưa giao rồi cải thiện bằng cách đổi chỗ vài cặp; lộ trình có thể không ngắn nhất nhưng tìm được trong vài giây và thường đủ tốt. Lưu ý bài toán này quyết định được — chỉ là chậm — nên đây không phải ví dụ của bài toán không quyết định được.

Common mistake

Bẫy “không quyết định được = quá chậm”. Bài lộ trình 40 điểm là bài chậm (thời gian không hợp lý) nhưng vẫn quyết định được. Không quyết định được là không thể viết thuật toán đúng cho mọi đầu vào. Bẫy thứ hai: dùng tìm nhị phân trên danh sách chưa sắp xếp. Bẫy thứ ba: đếm lần so của tìm nhị phân bằng $n/2$ — đó là số lần trung bình của tìm tuần tự, không phải của tìm nhị phân.

Key takeaway

Chốt: tìm tuần tự chạy mọi danh sách, xấu nhất $n$ lần so; tìm nhị phân cần danh sách đã sắp xếp, xấu nhất khoảng $\log_2 n$ lần ($k$ lần đủ cho $2^k-1$ phần tử). Đa thức = hợp lý; mũ/giai thừa = không hợp lý → dùng heuristic. Không quyết định được = không thuật toán nào đúng cho mọi đầu vào, khác hẳn với chậm.

← Procedures, Abstraction, Libraries and Simulations · All AP Computer Science Principles lessons · Practice AP Computer Science Principles questions (free, instant scoring) · The Internet, Protocols and Bandwidth →