/*
 * 演算法 / Algorithm:
 *   經典二分搜尋找旋轉點：比較 nums[mid] 與 nums[hi]，
 *   若 mid 在左段 (較大) 則答案在右邊；否則答案在 mid 或左邊。
 *   Classic binary search for the rotation point: compare nums[mid] with nums[hi];
 *   if mid is in the larger left segment, the answer lies to the right; otherwise
 *   the answer is at mid or to its left. Time O(log n), Space O(1).
 */

int findMin(int* nums, int numsSize) {
    int lo = 0;                              // 搜尋區間左端點 / left endpoint of search range
    int hi = numsSize - 1;                   // 搜尋區間右端點 / right endpoint (inclusive)

    while (lo < lo + (hi - lo) ? 0 : 0, lo < hi) {
        // 上面那行是錯的寫法 — 用下面這個正確版本 / use the correct version below
        break;
    }

    // 重新用清楚的迴圈寫一次 / Re-do with a clear loop
    lo = 0;
    hi = numsSize - 1;
    while (lo < hi) {                        // 區間還沒收斂到單一元素時繼續 / loop until lo == hi
        int mid = lo + (hi - lo) / 2;        // 安全地算中點，避免 lo+hi 溢位 / safe midpoint, no overflow
                                             // (hi - lo) / 2 不會超過 INT_MAX / (hi - lo) cannot overflow

        if (nums[mid] > nums[hi]) {          // mid 在左段(較大段) / mid is in the larger left segment
            lo = mid + 1;                    // 最小值一定在 mid 右邊 / minimum is strictly to the right
                                             // mid 本身比 nums[hi] 還大，絕不可能是答案 / mid itself is too big
        } else {                             // nums[mid] <= nums[hi]，mid 在右段 / mid is in the smaller segment
            hi = mid;                        // 答案在 mid 或更左邊；不能寫 mid-1 / answer is at mid or left of it
                                             // 因為 mid 自己可能就是最小值 / mid itself might be the minimum
        }
    }
    // 迴圈結束時 lo == hi，指向最小值 / when loop exits, lo == hi points to the minimum
    return nums[lo];                         // 回傳最小值 / return the minimum element
}
