5,534,119 members and growing! (16,820 online)
Email Password   helpLost your password?
General Programming » Algorithms & Recipes » General     Advanced

Binary Search Made Easy

By Eran Aharonovich

How to easily implement a binary search tree in your .NET projects
Windows, Visual Studio, Dev

Posted: 14 Dec 2006
Updated: 14 Dec 2006
Views: 12,840
Bookmarked: 3 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
7 votes for this Article.
Popularity: 1.56 Rating: 1.84 out of 5
6 votes, 85.7%
1
0 votes, 0.0%
2
0 votes, 0.0%
3
0 votes, 0.0%
4
1 vote, 14.3%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Introduction

Today I will show you how to search data using the binary tree algorithm.
It may not be the fastest algorithm you've ever seen but it's so easy to use and better than using .NET's simple structures.

Code

First we need to figure out how we sort items in our tree.
It doesn't matter if the data type is a string or a number as long as we decide how to sort items.
To do so, we create a class derived from IComparer. We add a 'Compare' function which returns 0 if the first item is equal to the second one, 1 if greater and -1 if smaller.

Create the binary search object which will accept the comparer class you created before.

BinaryIndex index = new BinaryIndex( new TestComparer(), true ); 


Add several items to this object, in our case it's a number:

index.Add( 10 ); 

index.Add( 2 );

index.Add( 21 ); 

To search the tree just call the Search method which will return an ArrayList object of the results:
ArrayList results = index.Search( 4 ); 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Eran Aharonovich


Been a programmer since 1999.
Experience in:
.Net, C++, C#, VB, VB.NET, ASP, ASP.NET, DLLs, COM etc.

Noviway


Occupation: Web Developer
Location: Israel Israel

Other popular Algorithms & Recipes articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 2 of 2 (Total in Forum: 2) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralRemove seems supsect with 'byMemory'memberRichard_N10:47 14 Dec '06  
Generalwhere is the article?memberMCHANNER6:59 14 Dec '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 14 Dec 2006
Editor:
Copyright 2006 by Eran Aharonovich
Everything else Copyright © CodeProject, 1999-2008
Web18 | Advertise on the Code Project