Array algorithms: max, count, search, average
Four classic array jobs
- Most array work is one of four scans: find the maximum, count matches, search for a value, or take an average.
- Each one is a single
forloop over the array, with a variable that remembers something. - Once you know these four, most array problems are a small change to one of them.
Bốn công việc mảng kinh điển
- Hầu hết công việc với mảng là một trong bốn phép quét: tìm giá trị lớn nhất, đếm số lần trùng khớp, tìm kiếm một giá trị, hoặc tính trung bình cộng.
- Mỗi loại đều là một vòng lặp
forđơn giản trên mảng, kèm theo một biến nhớ giữ dữ liệu. - Một khi bạn nắm vững bốn kỹ thuật này, hầu hết các bài toán mảng chỉ là một thay đổi nhỏ của một trong chúng.
Finding the maximum
- Start by assuming the first item is the biggest:
int best = a[0];. - Then look at the rest. If an item is bigger than
best, it becomes the newbest. - This works for negative numbers too, because you start from a real item, not
0.
Tìm giá trị lớn nhất
- Bắt đầu bằng cách giả sử mục đầu tiên là lớn nhất:
int best = a[0];. - Sau đó xem xét phần còn lại. Nếu một mục lớn hơn
best, nó sẽ trở thànhbestmới. - Cách này hoạt động với cả số âm, vì bạn bắt đầu từ một mục thực tế, chứ không phải
0.
Counting with a condition
- A counter starts at
0and adds1each time an item passes a test. - For example, count even numbers by testing
a[i] % 2 == 0inside the loop. - The counter's final value is your answer.
Đếm với điều kiện
- Một bộ đếm bắt đầu ở
0và tăng1mỗi khi một mục vượt qua điều kiện kiểm tra. - Ví dụ, đếm số chẵn bằng cách thử nghiệm
a[i] % 2 == 0bên trong vòng lặp. - Giá trị cuối cùng của bộ đếm chính là câu trả lời của bạn.
Linear search
- To search, walk the array and compare each item to the target.
- Return the index as soon as you find a match. If the loop ends with no match, return
-1. -1is a common "not found" signal because it is never a valid index.
Tìm kiếm tuyến tính
- Để tìm kiếm, hãy duyệt qua mảng và so sánh từng mục với giá trị mục tiêu.
- Trả về chỉ số ngay khi bạn tìm thấy sự trùng khớp. Nếu vòng lặp kết thúc mà không có matches, hãy trả về
-1. -1là tín hiệu "không tìm thấy" phổ biến vì nó chưa bao giờ là chỉ số hợp lệ.
Average without integer-division bugs
- Add all the items into an
inttotal, then divide byn. - Dividing two
ints drops the fraction, so cast:(double)total / n. - Return a
doubleso the caller gets the exact average.
Trung bình cộng mà không gặp lỗi chia nguyên
- Cộng tất cả các mục vào một tổng
int, sau đó chia chon. - Chia hai
intsẽ bỏ phần thập phân, nên cần ép kiểu:(double)total / n. - Trả về một
doubleđể người gọi nhận được giá trị trung bình chính xác.
Common mistakes
- Start a max or min from the first element, then compare the rest.
- Do not read past the end of the array.
Lỗi thường gặp
- Khởi tạo max hoặc min từ phần tử đầu tiên, sau đó so sánh với các phần tử còn lại.
- Đừng đọc vượt quá giới hạn của mảng.
Now you try
- Pass the array and its length
n, and pick the right "remember" variable for each job. - Do not write a
main— the checker provides one.
Bây giờ bạn thử
- Truyền vào mảng và độ dài
ncủa nó, và chọn đúng biến "nhớ" cho mỗi công việc. - Không viết một
main— trình kiểm tra sẽ cung cấp cho bạn một cái.
Scanning an array
One pass keeps a running result (max, sum, count) across the array.
Complete int max(const int a[], int n) so it returns the largest item (assume n >= 1). Start from a[0] so negatives work. Do not write a main.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
Complete int count_even(const int a[], int n) so it returns how many items are even. Use % 2. Do not write a main.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
Complete int index_of(const int a[], int n, int target) so it returns the index of the first target, or -1 if it is not there. Do not write a main.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
Complete double average(const int a[], int n) so it returns the average of the items (assume n >= 1). Cast to avoid integer division. Do not write a main.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.