وبلاگ شخصی حامد شیرزاد
وبلاگ شخصی حامد شیرزاد
صفحات وبلاگ
نویسنده: حامد شیرزاد - ۱۳٩٠/٧/۱٢


type
TStringArray = Array of String;

{--------------------------------------------------------------------}
//Start is the index of the first item of the array - usually 0
//Stop is the index of the last item of the array
procedure QuickSort(var Strings : TStringArray; Start, Stop : Integer);
Var
Left : Integer;
Right : Integer;
Mid : Integer;
Pivot : String;
Temp : String;

begin
Left := Start;
Right := Stop;
Mid := (Start + Stop) div 2;

Pivot := Strings[mid];
Repeat
While Strings[Left] < Pivot do inc(Left);
While Pivot < Strings[Right] do dec(Right);
If Left Right;

If Start < Right then QuickSort(Strings, Start, Right); // Uses
If Left < Stop Then QuickSort(Strings, Left, Stop); // Recursion
end;
{--------------------------------------------------------------------}
function BinSearch(Strings : TStringArray; SubStr : String) : Integer;
var
First : Integer;
Last : Integer;
Pivot : Integer;
Found : Boolean;

begin
First := Low(Strings); //Sets the first item of the range
Last := High(Strings); //Sets the last item of the range
Found := False; //Initializes the Found flag (Not found yet)
Result := -1; //Initializes the Result

//If First > Last then the searched item doesn't exist
//If the item is found the loop will stop
While (First SubStr then
Last := Pivot - 1
//else select the second half
else First := Pivot + 1;
end;
end;
{--------------------------------------------------------------------}

//To use the Binary Search:
procedure Button1Click(Sender : TObject);
var
MyStrings : TStringArray;

begin
//Give some values to your strings and remember to
//Set it to the correct length :)
//..
//..
//..

QuickSort(MyStrings, 0, High(MyStrings);
ShowMessage('The index of 'Derek' is: ' +
IntToStr(BinSearch(MyStrings,'Derek')
//If 'Derek' is in MyStrings, its index value will be returned,
//otherwise -1 will be returned.
end;

نویسندگان وبلاگ:
مطالب اخیر:
کدهای اضافی کاربر :