Karate Chop
June 16, 2015
Dave Thomas has a Code Kata in which he challenges programmers to write five different implementations of binary search (also known as the “binary chop” or, in Thomas’ kata-lingo, the “karate chop”). He doesn’t define “different” except to use phrases such as “totally different technique” and “totally unique implementations” and to suggest the traditional iterative approach, a recursive approach, a functional style passing array slices around, and so on.
Your task is to write five different implementations of binary search, returning the index of a target value in a sorted array of integers, or -1 if the target is not present. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
I don’t give the code for the standard interative, recursive and functional functions. But here is a somewhat different approach. Basically, for each bit in the index, starting at the msb, you decide whether that bit should be set or clear by comparing el with the value at lst[index with the bit set]. four() is an iterative version, five() is a recursive version; nine() is a functional version based on the same idea.
Somehow, I pasted the wrong version of nine(). Here’s the correct version:
@Mike: nice solution, I wish I’d thought of that…