Forum Topic: AS3: Binary Search

(332 views • 14 replies)

This topic is 1 page long.

<< < > >>
Elated

matrix5565

Reply To Post Reply & Quote

Posted at: 8/20/09 09:31 PM

matrix5565 LIGHT LEVEL 15

Sign-Up: 02/28/06

Posts: 558

AS3: Main

Intro
|Link to article on Wikipedia|
When you're working with large array's, you often have to search for specific elements. Speed can become an issue if your array's length is in the thousands and it will quickly bog down performance. Binary searches allow you to drastically increase the speed by which you find the information you're looking for. In my testing I found this to be about twice as fast as a Array.indexOf() for very large arrays.

How It Works
Binary searches start with the array's middle element, then, depending on whether the search term is higher or lower than that term, it will move to the appropriate place in the array (higher or lower). You can immediately see why the array MUST BE SORTED for this method to work, otherwise it will likely not find the term.

The Code

function bsearch(array:Array,searchValue:*,sortOption:uint = 16):*
{
	var tempArray:Array = array; //use a temporary array for sorting
	if (sortOption != 0) //a sort option of 0 will assume the array is already sorted
		tempArray = tempArray.sort(sortOption); //else it will sort by the given sort option (explained below)
	
	var b:int = 0;//bottom search index
	var t:int = tempArray.length-1;//top search index
	
	while (b <= t)//as long as the indexes have not crossed
	{
		var index:uint = (b+t)/2//search the middle of the indexes
		
		if (tempArray[index] == searchValue)//have you found the value?
		{
			if (sortOption != 0)//the value was found! If the array was presorted it will return the index, otherwise it will just return true
				return true;
			else
				return index;
		}
		else if (tempArray[index] < searchValue)//if the value checked is lower than the search term, it will check the higher portion
		{
			b = index+1;
		}
		else//otherwise it will check the lower portion
		{
			t = index-1;
		}
	}
	
	if (sortOption != 0)//if the item is never found it will return false or -1 (depending on whether or not the array was already sorted
		return false;
	else
		return -1;
}

For the sortOption use one of the Array sort options, or 0, if you've already sorted it.

Cons
This search method will not find all instances of the term, nor will it return the first or last instance. It will only return the first instance it finds. Also the speed increase will vary greatly depending on where the variable is located.

Conclusion
Thanks for reading, if you have any questions or comments, feel free to post below!


None

7IsUnlucky

Reply To Post Reply & Quote

Posted at: 8/20/09 10:13 PM

7IsUnlucky FAB LEVEL 25

Sign-Up: 06/12/07

Posts: 1,953

That is
The coolest thing I have ever seen

but I still don't like AS3 >:(

Programming languages I know: AS2 and TRS-80 BASIC

BBS Signature

None

liaaaam

Reply To Post Reply & Quote

Posted at: 8/20/09 11:01 PM

liaaaam NEUTRAL LEVEL 22

Sign-Up: 12/11/04

Posts: 14,533

Jeez, that did not compile at all in Flash CS4.. your if/else syntax is kinda fucked up.. and with your use of the "standard" (I suppose) placement of curly braces, it's just messy as hell :/

Nice though.


None

thedayturns

Reply To Post Reply & Quote

Posted at: 8/21/09 01:10 AM

thedayturns NEUTRAL LEVEL 01

Sign-Up: 08/08/09

Posts: 12

At 8/20/09 11:01 PM, liaaaam wrote: Jeez, that did not compile at all in Flash CS4.. your if/else syntax is kinda fucked up.. and with your use of the "standard" (I suppose) placement of curly braces, it's just messy as hell :/

Hardly. The if/else syntax is pretty typical... and if he would have corrected the curly bracket placement, Flash would have died on an autocomplete because a code like (if(bla) { // stuff) breaks it.

Anyway, nice code, but it's hardly AS3 specific. In fact, it would be kind of neat to have like a theoretical programming section.


None

GustTheASGuy

Reply To Post Reply & Quote

Posted at: 8/21/09 02:51 AM

GustTheASGuy LIGHT LEVEL 08

Sign-Up: 11/02/05

Posts: 11,387

Three words: balanced binary tree.

#ngprogramming at irc.freenode.net
haXe | Keel imperative | Spyro! | Thru you


None

Afro-Ninja

Reply To Post Reply & Quote

Posted at: 8/21/09 03:53 AM

Afro-Ninja EVIL LEVEL 38

Sign-Up: 03/02/02

Posts: 13,463

At 8/21/09 01:10 AM, thedayturns wrote: In fact, it would be kind of neat to have like a theoretical programming section.

er.. the programming forum

BBS Signature

None

henke37

Reply To Post Reply & Quote

Posted at: 8/21/09 05:14 AM

henke37 NEUTRAL LEVEL 23

Sign-Up: 09/10/04

Posts: 3,607

Too bad that actionscript in banned there. Why? Because we got tired of reading the same stupid questions and "give me the codes" post all the time. We need an advanced forum for people who know what they are doing.

Each time someone abuses hittest, God kills a kitten. Please, learn real collision testing.


None

GustTheASGuy

Reply To Post Reply & Quote

Posted at: 8/21/09 05:54 AM

GustTheASGuy LIGHT LEVEL 08

Sign-Up: 11/02/05

Posts: 11,387

I don't think there's a need. There are more suitable communities for people who know what they're doing.

#ngprogramming at irc.freenode.net
haXe | Keel imperative | Spyro! | Thru you


None

FlashtooREV

Reply To Post Reply & Quote

Posted at: 8/21/09 06:12 AM

FlashtooREV LIGHT LEVEL 06

Sign-Up: 06/09/09

Posts: 603

At 8/21/09 05:14 AM, henke37 wrote: We need an advanced forum for people who know what they are doing.

Someone tried to do that with a thread, but Kirk locked it as he saw no future in it.

Ceterum censeo Carthaginem esse delendam.


None

Deadclever23

Reply To Post Reply & Quote

Posted at: 8/21/09 08:35 AM

Deadclever23 FAB LEVEL 12

Sign-Up: 11/27/06

Posts: 1,038

At 8/21/09 06:12 AM, FlashtooREV wrote:
At 8/21/09 05:14 AM, henke37 wrote: We need an advanced forum for people who know what they are doing.
Someone tried to do that with a thread, but Kirk locked it as he saw no future in it.

Guilty as charged.

IndyDev - Reviews, News and Tutorials. the hottest new Indy blog of it's kind. (Shameless self promotion).

BBS Signature

None

Paranoia

Reply To Post Reply & Quote

Posted at: 8/21/09 08:50 AM

Paranoia DARK LEVEL 34

Sign-Up: 04/22/05

Posts: 9,697

At 8/21/09 06:12 AM, FlashtooREV wrote:
At 8/21/09 05:14 AM, henke37 wrote: We need an advanced forum for people who know what they are doing.
Someone tried to do that with a thread, but Kirk locked it as he saw no future in it.

There isn't enough demmand for it. Whenever something suitably amazing comes up we can just use the reg lounge or a new thread, and the handful of people who will get it can gravitate towards it.

BBS Signature

Happy

matrix5565

Reply To Post Reply & Quote

Posted at: 8/21/09 01:00 PM

matrix5565 LIGHT LEVEL 15

Sign-Up: 02/28/06

Posts: 558

At 8/20/09 10:13 PM, 7IsUnlucky wrote: That is
The coolest thing I have ever seen
but I still don't like AS3 >:(
At 8/21/09 01:10 AM, thedayturns wrote: Anyway, nice code, but it's hardly AS3 specific. In fact, it would be kind of neat to have like a theoretical programming section.

Actually, this code should port to AS2 quite nicely depending on if/how you sort array's.


Happy

matrix5565

Reply To Post Reply & Quote

Posted at: 8/21/09 01:30 PM

matrix5565 LIGHT LEVEL 15

Sign-Up: 02/28/06

Posts: 558

Wow, I decided to do a super scientific speed test and here are the results (in milliseconds):
Binary Search: <1
indexOf: 12368

The code:

import flash.utils.getTimer;

var startTime:int;
var finishTimes:Array = [];
var testArray:Array = [];

for (var i:int = 0; i <= 10000000; i++)
	testArray.push(i);
	
var rand:int = Math.random()*10000000;	

startTime = getTimer();
for (var a:int = 0; a <= 100; a++)
	bsearch(testArray,rand,0);
finishTimes.push(getTimer()-startTime);

startTime = getTimer();
for (var b:int = 0; b <= 100; b++)
	testArray.indexOf(rand);
finishTimes.push(getTimer()-startTime);

trace(finishTimes); //0, 12368

That was only one test, but the numbers varied a lot, between ~300 and ~15000, but the binary search never took more than 1 millisecond.


None

henke37

Reply To Post Reply & Quote

Posted at: 8/21/09 03:19 PM

henke37 NEUTRAL LEVEL 23

Sign-Up: 09/10/04

Posts: 3,607

That is because a binary search in a balanced tree is O(ln n) while a linear search is O(n). The cost is balancing the tree. Also, don't forget the cpu memory cache, a proper binary tree needs a lot of pointers, and pointers are horrible for the cache. If it is just a couple of items, stick to a linear search.

Each time someone abuses hittest, God kills a kitten. Please, learn real collision testing.


None

Arby

Reply To Post Reply & Quote

Posted at: 8/21/09 04:56 PM

Arby LIGHT LEVEL 25

Sign-Up: 10/24/04

Posts: 2,234

Just an FYI, that exact same code will work in AS2 if you get rid of all the types.

Lol @ AS2 failing to have an int type. Didn't actually know that before...

Gust, your binary tree is no match for my TRINARY TREE!

Shush! it's useful in... I don't know.... hopefully something.. =/ but it's log3(n) search time!

At first there was nothing, then it exploded. - Big bang


All times are Eastern Standard Time (GMT -5) | Current Time: 12:55 PM

<< Back

This topic is 1 page long.

<< < > >>
You need a Grounds Gold Account to post on the NG BBS! If you don't have one, click here to sign up now! It's fast, free, and easy — and opens up tons of great NG features!