Home > Recursion > A Funny Thing Happened on the way to Skip Lists: The ActionScript 3.0 Binary Search Algorithm

A Funny Thing Happened on the way to Skip Lists: The ActionScript 3.0 Binary Search Algorithm

binarySearch A while back a comment by Timo Hannelin suggested that I use a skip list in one of the design patterns. (I looked but couldn’t find the comment, but I remember it was a good idea.) Anyway, I read the original article on skip lists by William Pugh. After reading the article and a few more articles on skip lists, I saw Timo’s point. However, since I’ve got my hands full with design patterns, and I dislike design pattern discussions degenerating into a chat about algorithms, I didn’t bring it up.

Algorithms in Participants

Having a little time right now, I thought I’d return to skip lists and see where they’d be valuable for participants in one of the design patterns. So, to warm up for working with skip lists I thought I’d whip up a Binary Search algorithm in ActionScript 3.0. Further, I wanted to entertain myself, and so I decided not to peek at any solutions on the Web.

After a few hours of trying to strong arm a solution I gave up and decided to peek. This is what I found:

Although the basic idea of binary search is comparatively straightforward, the details can be surprisingly tricky… — Professor Donald Knuth (Professor emeritus, Stanford University)

Further, I learned that only five out of twenty textbooks had accurate code for a binary search! Well, at least I didn’t feel like an idiot, but still, the concept is pretty simple, and it’s easy to do in your head. It’s just difficult (or tricky) to whip one up in code.

The Binary Search

The concept behind the binary search is to search by dividing an ordered list in consecutive halves. If the search guess is higher (in the ordered list) than the one being searched for, the bottom of a range is the search guess. If the search guess is lower; then the top of the range is the search guess. Each consecutive search is the halfway point between the top and bottom of the range. The solution is found by closing in like a vice taking chunks in halves rather than iterating through an entire list. It’s very fast and efficient for searches.

To get started, I created a function to generate a quick and dirty ordered array with 100 random numbers. (The variables were declared elsewhere in the class.)

?View Code ACTIONSCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
private function generate():Array
{
	//Generates 100 numbers
	//Places them in a sorted array
	while (pack < 100)
	{
		ranInt=Math.random()*100;
		arrayPack.push(ranInt);
		pack++;
	}
	arrayPack.sort();
	return arrayPack;
}

Then I started writing the algorithm for the binary search. After locking up my computer with infinite loops a couple of times and rerouting the power grid of Bloomfield, Connecticut to Timbuktu, I gave up. Using numbers, I kept mixing up array numeric keys with the search values.

Your Turn to Have Some Fun

Anyway, since a lot of our readers like algorithms, I thought this might be a fun one for you to solve. You can find a lot of discussions of the binary search concept online as well as solutions (in the form of code and generic algorithms). However, see what you can come up with before you give up and peek (like I did). I can tell you this, though. One general solution uses recursive coding and the other uses iterative. Remember, though—only about a quarter of the computer science textbooks had it right. So, give it a go on your own knowing that if you come up with a solution, you’re smarter than 75% of the CS textbooks! We’ll use the Comments Section of this post for your solutions and look at skip lists in a future post.

Share

No related posts.

Categories: Recursion
  1. May 5, 2010 at 8:46 am | #1

    It’s not an exact answer to your question, but here you have an application of a binary search. In my experiments with a monte carlo diff for strings, a binary search serves to expand the randomly located identical substrings between the two strings compared, which later solves the longest common subsequence problem:

    http://blog.controul.com/2009/05/diff-patch-for-flash-as3/

    It’s not the best code ever, but it’s a fun play on algorithms.

  2. cyberpunk
    May 5, 2010 at 10:23 am | #2

    After reading the article i played a little with binary search. In the end i came up with this method http://www.copypastecode.com/28036/

    I also did some benchmarks over it and it’s nice to see how the binary search can make 500 searches in a list of 1000000 items in 2-5 milliseconds where the indexOf method took up to 450ms.
    Also, the binary operation to divide the number helped a bit. With a regular division the same benchmark took from 4 to 9 ms to complete.

    The worst part is compare data. With numbers there’s no problem. strings may lead to some error due to the comparison and for objects you need some property to use to compare the two. I wish we had something like the Comparable interface of Java.

    In the end, this method of searching is great, but the process of sorting the data can spoil all the fun … any ideas to minimize this problem?

  3. May 5, 2010 at 11:24 am | #3

    Hi Cyberpunk,

    I like your solution. Even the variable names are cool. Is it an iterative or recursive solution?

    I deal with the sorting problem by putting everything into an array and use the .sort() method.

    Kindest regards,
    Bill

  4. May 5, 2010 at 11:28 am | #4

    Hi Hristo,

    I couldn’t find the code you mentioned. Could you bring the part of the code here that deals with binary searches (and we’ll credit your blog!). I’d be interested to see it.

    Kindest regards,
    Bill

  5. cyberpunk
    May 5, 2010 at 12:11 pm | #5

    it’s iterative (the method is called once and the search is performed in the while statement)

    about the sort i’m not that confidend, i think that whit huge lists or with many iterations it could impact badly on the performances and waste all the gain of the binary search.

    i’m looking into the BinarySearchTree structures now … it seems to be a cool way to handle the problem.

  6. May 5, 2010 at 1:35 pm | #6

    Hi Cyberpunk,

    Thanks again. I’ve been leaning toward the recursive because of the reason you site.

    Before getting too involved with the BinarySearchTree, take a look at the skip list. If I’m not mistaken, the skip list replaced the BST.

    Kindest regards,
    Bill

  7. May 5, 2010 at 2:47 pm | #7

    Hi Bill,

    You might be interested in a series of posts over at The Reinvigorated Programmer’s blog:

    http://reprog.wordpress.com/2010/04/19/are-you-one-of-the-10-percent/

    It’s pretty good, and probably up your alley.

    Cheers,
    Shaun

  8. cyberpunk
    May 5, 2010 at 3:38 pm | #8

    i’m looking forward for your future post about skip lists then :)

  9. May 5, 2010 at 4:35 pm | #9

    Hi Shaun,

    I took a look at the book featured in that blog post and then found this:

    Furthermore, Bentley’s own implementation of binary search, published in his 1986 book Programming Pearls, contains an error that remained undetected for over twenty years.

    So is this edition the one with the error hidden until 2006? However, it’s a great post about binary searches. Thanks.

    Kindest regards,
    Bill

  10. May 5, 2010 at 4:40 pm | #10

    Hi Cyberpunk,

    While you’re waiting, take at look at the original:

    ftp://ftp.cs.umd.edu/pub/skipLists/skiplists.pdf

    It’s always best to go to the original source! Maybe you can beat the rest of us in getting an ActionScript 3.0 Skip List example going.

    Kindest regards,
    Bill

  11. May 10, 2010 at 12:15 pm | #11

    Sorry Bill,

    Didn’t see your response here until I got to read your new post.
    If you’re still curious, the binary search is in Patch.as, under the headings ‘expand to the left’ and ‘expand to the right’. It shows binary search in a loop, without recursion, using two vars (‘a’ and ‘b’) for the offsets/indices that bound the search on the two sides.

    Hristo

  12. May 10, 2010 at 3:57 pm | #12

    Hi Histro,

    Thanks–no worries. Binary searches using iteration are perfectly fine.

    Cheers,
    Bill

  1. May 5, 2010 at 8:08 am | #1
  2. May 8, 2010 at 11:37 am | #2

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>