อัลกอริทึม C/C++

Binary Search

Binary search ตัดครึ่งช่วงหลังทุก comparison

Binary Search คืออะไร?

Binary search ตัดครึ่งช่วงหลังทุก comparison

ค้นข้อมูลเรียงแล้วในเวลา logarithmic

ประเด็นสำคัญ

  • ทดสอบ input ว่าง หนึ่งสมาชิก ซ้ำ และเรียงแล้ว
  • แยก correctness จาก optimization
  • ใช้ standard library ใน production เมื่อเหมาะสม

ภาพจำลอง Binary Search

O(log n)

กด เล่น หรือ ทีละขั้น เพื่อดูการเปรียบเทียบและการย้ายข้อมูลแต่ละขั้น

ตัวอย่างโค้ด C และ C++

C
รันโค้ด →
main.c
#include <stdio.h>

int search(const int *values, int size, int target) {
    int low = 0;
    int high = size - 1;
    while (low <= high) {
        int middle = low + (high - low) / 2;
        if (values[middle] == target) return middle;
        if (values[middle] < target) low = middle + 1;
        else high = middle - 1;
    }
    return -1;
}

int main(void) {
    int values[] = {3, 7, 11, 16, 23, 28};
    printf("index=%d\n", search(values, 6, 23));
}
ผลลัพธ์ที่คาดหวัง
index=4
C++
รันโค้ด →
main.cpp
#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector values{3, 7, 11, 16, 23, 28};
    auto match = std::lower_bound(values.begin(), values.end(), 23);
    std::cout << "index="
              << std::distance(values.begin(), match) << '\n';
}
ผลลัพธ์ที่คาดหวัง
index=4

เปรียบเทียบ C และ C++

Input ต้อง sorted โดย loop C และ std::lower_bound เป็น O(log n) บน random-access range

C

Loop, pointer, length และ buffer เขียนอย่างชัดเจน

C++

Iterator และ algorithm แยก operation จาก storage

แบบฝึกหัด

รันทั้งสองเวอร์ชันแล้วแก้ไขเพื่อสังเกตความแตกต่างของภาษา

  • ไล่ตามทุก comparison
  • ทดสอบ duplicate และ extreme value
  • Benchmark กับ standard library