Follow me on Twitter to receive updates, free scripts and ongoing announcements!

Binary search in string array

Written by Codes Tips on May 10, 2009 – 2:04 pm -

To search an string into an array of string you can iterate through all the strings one by one and test which is the string that we wanna search. Doing this you will have a complexity of O(n), where n is the number of the strings that array have.
To do search more efficient you should use binary search which have a complexity of O(log2(n)). To use the binary search method in an array of string we assume that we have a sorted array. To sort an array of string efficiently you can use for example Quicksort algorithm , that was previously described, to obtain a good complexity. Of course, you should use binary search algorithm when you are doing something complex that have a complexity bigger or equal to O(n^2).
So to search a string in an array the algorithm selects the middle element of the array and verify if it is equal to our string. If it is equal it stops, if not it sees if the string is bigger then our string and if it is, it searches in the right part of the array string, if not in left part, applying the same algorithm. So it uses a recursive function to search the string in the array.

We will use the following type of string and declare a variable:

type  arraystrings=array[1..1000000] of string;
var words:arraystrings;

Here is the binary search algorithm:

 
function BinSearch(word:string;l:integer;h:integer):integer;
 begin
    while (StrIComp(pchar(word),pchar(words[(l+h)div 2]))<>0)and(l<>h) do
      begin
         if strIcomp(pchar(word),pchar(words[(l+h)div 2]))>0 then
            l:=(l+h)div 2+1
          else
            h:=(l+h)div 2-1;
      end;
    if l<>h then
     BinSearch:=(l+h)div 2
    else
     BinSearch:=0;
 end;

It returns the position in the array where it was found. If not returns 0.
To call it you can use:

position:=BinSearch(word,1,nrwords);

where word is the string we search for and nrwords it’s the number of strings in the array.


Tags: ,
Posted in Algorithms, Codes, Delphi |

Leave a Comment

You must be logged in to post a comment.


Plugintaylor.com - Plugintaylor and New Version