第1章 算法简介 code
- 章节名:第1章 算法简介 code
'use strict'; function binary_search(list, item) { let low = 0; let high = list.length - 1; while (low <= high) { let mid = Math.floor((low + high) / 2); let guess = list[mid]; if (guess === item) { return mid; } if (guess > item) { high = mid - 1; } else { low = mid + 1; } } return null;} const my_list = [1, 3, 5, 7, 9]; console.log(binary_search(my_list, 3)); // 1console.log(binary_search(my_list, -1)); // null <?phpfunction binarySearch($needle, $array) { $low = 0; $high = count($array) - 1; while ($low <= $high) { $middle = floor(($low + $high) / 2); if ($array[$middle] == $needle) { return $middle; } if ($array[$middle] > $needle) { $high = $middle - 1; } else { $low = $middle + 1; } } return null;}$array = [1, 3, 5, 7, 9];echo binarySearch(3, $array) . "\n";echo binarySearch(-1, $array) . "\n"; 引自 第1章 算法简介 code
32人阅读
说明 · · · · · ·
表示其中内容是对原文的摘抄