二分查詢
export function BinarySearch(key: number, arr: number[]) { // 陣列必須是有序的 let low: number = 0; let hi: number = arr.length - 1;
while (low <= hi) { const mid = low + (hi - low) / 2; if (key < arr[mid]) { hi = mid - 1; } else if (key > arr[mid]) { low = mid + 1; } else { return mid; } } return -1;}複製程式碼