![]() |
|
#1
|
|||
|
|||
![]() нужно сделать таблицу из 20 записей с ключами, отсортированными по возрастанию. Реализовать двоичный поиск, вывести результат и количество сравнений.
что-то делать начала... ![]() Код:
function ListviewBinarySearch(listview: TListview; const Item: string; var Index: Integer): Boolean; var First, last, pivot, res, k: Integer; Memo1:TMemo; begin Memo1.Clear; k:=0; Assert(Assigned(listview)); Assert(Length(item) > 0); Result := False; Index := 0; if listview.Items.Count = 0 then Exit; First := 0; last := listview.Items.Count - 1; repeat k:=k+1; pivot := (First + last) div 2; res := lstrcmp(PChar(item), PChar(listview.Items[pivot].Caption)); if res = 0 then begin { Found the item, return its index and exit. } Index := pivot; Result := True; Break; end { If } else if res > 0 then begin { Item is larger than item at pivot } First := pivot + 1; end { If } else begin { Item is smaller than item at pivot } last := pivot - 1; end; until last < First; Index := First; Memo1.Lines.Add('количество сравнений=: '+IntToStr(k)); end; { ListviewBinarySearch } procedure TForm1.Button1Click(Sender: TObject); var i:integer; m: boolean; listveiew1:Tlistview; begin if Edit1.Text<>'' then begin i:=StrToInt(Edit1.Text); m:=ListviewBinarySearch(ListView1,Item, i); if m=true then Memo1.Lines.Add('Результат поиска=: '+'найдено') else Memo1.Lines.Add('Результат поиска=: '+'не найдено'); end; |