Chapter 7: Binary Brewing Extreme - Debugging for Dummies
By: B. D. U. D.
Introduction to Extreme Brewing
Binary brewing: where art meets algorithm.
// Binary brewing is not for the faint of heart
var extreme = true;
if (extreme) {
console.log('You are now an extreme binary brewer');
// Proceed with caution...
}
Now that we've established that binary brewing is the pinnacle of coding achievement, let's dive into some real-world examples.
Example 1: Brewing a Simple Binary Search
Binary search: the ultimate algorithm for finding what's not there.
// Binary search in action
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var target = 7;
var low = 0;
var high = arr.length - 1;
while (low <= high) {
var mid = Math.floor((low + high) / 2);
if (arr[mid] === target) {
console.log('Found it!');
break;
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
if (low > high) {
console.log('Not found');
}
And that's it! A simple yet elegant solution to a problem that's been bugging you for weeks.
Example 2: Brewing a Complex Algorithm
When in doubt, just add more recursion.
// Complex algorithm in action
function recursiveBrewing(arr, target) {
if (arr[0] === target) {
return true;
} else if (arr.length === 1) {
return false;
} else {
var mid = Math.floor(arr.length / 2);
return recursiveBrewing(arr.slice(0, mid), target) || recursiveBrewing(arr.slice(mid + 1), target);
}
}
A little bit of recursion and we're back in business!
And that's it for today's chapter! Remember, practice makes perfect, so go out there and brew some binaries!