⚑️ Build your own docs with Notaku
You can create a full code block like this typing /code on Notion
javascript
function binary_search_iterative(a, value) { var mid, lo = 0, hi = a.length - 1; while (lo <= hi) { mid = Math.floor((lo + hi) / 2); if (a[mid] > value) { hi = mid - 1; } else if (a[mid] < value) { lo = mid + 1; } else { return mid; } } return null; }
You can also create inline code blocks selecting the text and clicking "Mark as code" like this one .

Languages

All the Notion code languages are available
javascript
function binary_search_iterative(a, value) { var mid, lo = 0, hi = a.length - 1; while (lo <= hi) { mid = Math.floor((lo + hi) / 2); if (a[mid] > value) { hi = mid - 1; } else if (a[mid] < value) { lo = mid + 1; } else { return mid; } } return null; }
rust
//edit to return desired value (the code has bool because usually you need to know whether the element exists or not) fn binary_search<T:PartialOrd>(v: &[T], searchvalue: T) -> bool { let mut lower = 0 as usize; let mut upper = v.len() - 1; while upper >= lower { let mid = (upper + lower) / 2; if v[mid] == searchvalue { return true; } else if searchvalue < v[mid] { upper = mid - 1; } else { lower = mid + 1; } } return false; }
haskell
import Data.Array (Array, Ix, (!), listArray, bounds) -- BINARY SEARCH USING A HELPER FUNCTION WITH A SIMPLER TYPE SIGNATURE findIndexBinary :: Ord a => (a -> Ordering) -> Array Int a -> Either String Int findIndexBinary p axs = let go (lo, hi) | hi < lo = Left "not found" | otherwise = let mid = (lo + hi) `div` 2 in case p (axs ! mid) of LT -> go (lo, pred mid) GT -> go (succ mid, hi) EQ -> Right mid in go (bounds axs)
java
public class BinarySearchRecursive { public static int binarySearch(int[] haystack, int needle, int lo, int hi) { if (hi < lo) { return -1; } int guess = (hi + lo) / 2; if (haystack[guess] > needle) { return binarySearch(haystack, needle, lo, guess - 1); } else if (haystack[guess] < needle) { return binarySearch(haystack, needle, guess + 1, hi); } return guess; } public static void main(String[] args) { int[] haystack = {1, 5, 6, 7, 8, 11}; int needle = 5; int index = binarySearch(haystack, needle, 0, haystack.length); if (index == -1) { System.out.println(needle + " is not in the array"); } else { System.out.println(needle + " is at index " + index); } } }
Powered by Notaku