Продолжаем мультиязычные посты. Сегодня бинарный поиск. Все программы будут состоять из 2 частей – рандомное заполнение массивов с сортировкой. И вторая часть – собственно бинарный поиск.
Delphi (бинарный поиск)
Собственно реализация
Функции бинарного поиска Integer и String массивов. Массивы предварительно отсортированы
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
function TfMain.BinarySearchInteger(ASomeArray: TArray<Integer>; AKey: integer): Integer; var i: Integer; LowIndex,HighIndex:integer; begin LowIndex:=0; HighIndex:=High(ASomeArray); i:=(LowIndex+HighIndex) div 2; while LowIndex<=HighIndex do begin if ASomeArray[i]=Akey then Break; if ASomeArray[i]>Akey then HighIndex:=i-1 else if ASomeArray[i]<Akey then LowIndex:=i+1; i:=(LowIndex+HighIndex) div 2; end; if LowIndex<=HighIndex then Result:=i else Result:=-1; end; function TfMain.BinarySearchString(ASomeArray: TArray<String>; AKey: String): Integer; var i: Integer; LowIndex,HighIndex:integer; begin LowIndex:=0; HighIndex:=High(ASomeArray); i:=(LowIndex+HighIndex) div 2; while LowIndex<=HighIndex do begin if ASomeArray[i]=Akey then Break; if ASomeArray[i]>Akey then HighIndex:=i-1 else if ASomeArray[i]<Akey then LowIndex:=i+1; i:=(LowIndex+HighIndex) div 2; end; if LowIndex<=HighIndex then Result:=i else Result:=-1; end; |
Все вместе
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 |
unit uMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, system.generics.defaults,System.Generics.Collections; type TfMain = class(TForm) bBinarySearchInteger: TButton; bFillIntegerArray: TButton; Memo: TMemo; bFillStringArray: TButton; bBinarySearchString: TButton; procedure bBinarySearchIntegerClick(Sender: TObject); procedure bFillIntegerArrayClick(Sender: TObject); procedure bFillStringArrayClick(Sender: TObject); procedure bBinarySearchStringClick(Sender: TObject); private { Private declarations } FSomeIntegerArray:TArray<integer>; FSomeStringArray:TArray<String>; procedure FilIntegerlArray; procedure FillStringArray; function GiveRandomWord(ALength:integer):String; function BinarySearchInteger(ASomeArray:TArray<Integer>;AKey:integer):Integer; function BinarySearchString(ASomeArray: TArray<String>; AKey: String): Integer; public { Public declarations } end; var fMain: TfMain; implementation {$R *.dfm} { TfMain } procedure TfMain.bBinarySearchIntegerClick(Sender: TObject); var IntegerToSearchString:String; begin if InputQuery('SomeCaption','',IntegerToSearchString) then ShowMessage( BinarySearchInteger(FSomeIntegerArray,IntegerToSearchString.ToInteger()).ToString ); end; procedure TfMain.bBinarySearchStringClick(Sender: TObject); var StringtoSearch: string; begin if InputQuery('SomeCaption','',StringtoSearch) then ShowMessage( BinarySearchString(FSomeStringArray,StringtoSearch).ToString ); end; procedure TfMain.bFillIntegerArrayClick(Sender: TObject); begin FilIntegerlArray; end; procedure TfMain.bFillStringArrayClick(Sender: TObject); begin FillStringArray; end; function TfMain.BinarySearchInteger(ASomeArray: TArray<Integer>; AKey: integer): Integer; var i: Integer; LowIndex,HighIndex:integer; begin LowIndex:=0; HighIndex:=High(ASomeArray); i:=(LowIndex+HighIndex) div 2; while LowIndex<=HighIndex do begin if ASomeArray[i]=Akey then Break; if ASomeArray[i]>Akey then HighIndex:=i-1 else if ASomeArray[i]<Akey then LowIndex:=i+1; i:=(LowIndex+HighIndex) div 2; end; if LowIndex<=HighIndex then Result:=i else Result:=-1; end; function TfMain.BinarySearchString(ASomeArray: TArray<String>; AKey: String): Integer; var i: Integer; LowIndex,HighIndex:integer; begin LowIndex:=0; HighIndex:=High(ASomeArray); i:=(LowIndex+HighIndex) div 2; while LowIndex<=HighIndex do begin if ASomeArray[i]=Akey then Break; if ASomeArray[i]>Akey then HighIndex:=i-1 else if ASomeArray[i]<Akey then LowIndex:=i+1; i:=(LowIndex+HighIndex) div 2; end; if LowIndex<=HighIndex then Result:=i else Result:=-1; end; procedure TfMain.FilIntegerlArray; var i: Integer; begin setlength(FSomeIntegerArray,100); for i := 0 to 99 do begin FSomeIntegerArray[i]:=Random(1000); end; TArray.Sort<integer>(FSomeIntegerArray); Memo.Clear; for i := 0 to 99 do begin Memo.Lines.Add( FSomeIntegerArray[i].ToString ); end; end; function TfMain.GiveRandomWord(ALength:integer):String; var s:string; i:integer; begin for i:=1 to ALength do s:=s+Char(byte('A')+random(2)*32+random(26)); result:=s; end; procedure TfMain.FillStringArray; var i:integer; begin // setlength(FSomeStringArray,100); for i := 0 to 99 do begin FSomeStringArray[i]:=GiveRandomWord(20); end; TArray.Sort<String>(FSomeStringArray); Memo.Clear; for i := 0 to 99 do begin Memo.Lines.Add( FSomeStringArray[i]); end; end; end. |
С# (бинарный поиск)
Функция бинарного поиска отсортированного массива integer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
private int BinarySearch( int[] SomeIntArray, int Key ) { int LowIndex = 0; int HighIndex = (SomeIntArray.Length)-1; //HighIndex = Array.LastIndexOf(SomeIntArray);// HighIndex; int i=(LowIndex+HighIndex) / 2; while (LowIndex <= HighIndex) { if (SomeIntArray[i] == Key) break; if (SomeIntArray[i] > Key) { HighIndex=i-1; } else if (SomeIntArray[i] < Key) LowIndex=i+1; i = (LowIndex + HighIndex) / 2; } if ( LowIndex <= HighIndex ) { return i; } else return -1; } |
Полный код
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace BinarySearch { public partial class fBinarySearch : Form { public fBinarySearch() { InitializeComponent(); } int[] SomeRandomIntArray = new int[1000]; // initializing array private void FillRandomArrayAndSort() { // Random SomeRandomNumber = new Random(); for (int i = 0; i <= 999; i++) { SomeRandomIntArray[i] = SomeRandomNumber.Next(0,999); }; Array.Sort(SomeRandomIntArray); } private void bRandomFillAndSort_Click(object sender, EventArgs e) { // FillRandomArrayAndSort(); for (int i = 0; i <= SomeRandomIntArray.Length-1; i++) { richTextBox.AppendText("\n" + SomeRandomIntArray[i].ToString()); } } private int BinarySearch( int[] SomeIntArray, int Key ) { int LowIndex = 0; int HighIndex = (SomeIntArray.Length)-1; //HighIndex = Array.LastIndexOf(SomeIntArray);// HighIndex; int i=(LowIndex+HighIndex) / 2; while (LowIndex <= HighIndex) { if (SomeIntArray[i] == Key) break; if (SomeIntArray[i] > Key) { HighIndex=i-1; } else if (SomeIntArray[i] < Key) LowIndex=i+1; i = (LowIndex + HighIndex) / 2; } if ( LowIndex <= HighIndex ) { return i; } else return -1; } private void bBinarySearch_Click(object sender, EventArgs e) { int Result = BinarySearch(SomeRandomIntArray, Convert.ToInt32(textBox1.Text)); MessageBox.Show(Result.ToString()); } } } |
PHP (бинарный поиск)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
function BinarySearch(array $RandomArray, $KeyWord ){ echo " This is function ".$KeyWord." "; $lowIndex=0; $highIndex=( count( (array)$RandomArray) ); $count=0; $i=floor( ($lowIndex+$highIndex)/2 ); // like div in Delphi while ($lowIndex<=$highIndex){ if ( $RandomArray[$i]==$KeyWord ) break; if ( $RandomArray[$i]>$KeyWord ) {$highIndex=$i-1;} else if ( $RandomArray[$i]<$KeyWord ) {$lowIndex=$i+1;} $i=floor( ($lowIndex+$highIndex)/2 ); // $count++; } // echo "Count=".$count; if ($lowIndex<=$highIndex){return $i;} else return -1; } |
Полный код
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
<?php /** * Created by PhpStorm. * User: YellowFriend * Date: 24.01.2017 * Time: 15:38 */ //echo "hello, now we will count factorial"; ini_set('error_reporting', E_ALL); ini_set('display_errors', 1); ini_set('display_startup_errors', 1); $SomeRandomArray=array(); // filling array for ($i=0;$i<=99;$i++){$SomeRandomArray[]=rand(0,99);} // sorting sort($SomeRandomArray); // show array on screen foreach($SomeRandomArray as $key=>$value) { echo $key."=".$value."<br>"; } $Result=BinarySearch($SomeRandomArray,"5"); echo "<br>Result=".$Result; function BinarySearch(array $RandomArray, $KeyWord ){ echo " This is function ".$KeyWord." "; $lowIndex=0; $highIndex=( count( (array)$RandomArray) ); $count=0; $i=floor( ($lowIndex+$highIndex)/2 ); // like div in Delphi while ($lowIndex<=$highIndex){ if ( $RandomArray[$i]==$KeyWord ) break; if ( $RandomArray[$i]>$KeyWord ) {$highIndex=$i-1;} else if ( $RandomArray[$i]<$KeyWord ) {$lowIndex=$i+1;} $i=floor( ($lowIndex+$highIndex)/2 ); // $count++; } // echo "Count=".$count; if ($lowIndex<=$highIndex){return $i;} else return -1; } |
JavaScript (BinarySearch)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// BINARY SEARCH function BinarySearch (SomeArray,Key){ var LowIndex=0; var HighIndex=SomeArray.length; //document.writeln('<br>'+HighIndex); var i=Math.floor( (LowIndex + HighIndex) / 2); while (LowIndex<=HighIndex) { if (SomeArray[i]=Key) break; if (SomeArray[i]>Key){HighIndex=i-1} else if (SomeArray[i]<Key){LowIndex=i+1} i=Math.floor( (LowIndex+HighIndex)/2); } if (LowIndex<=HighIndex){return i} else return-1; } |
Весь код
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Hello from HTML</title> <script> //----------Creating array of random integers function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min)) + min; } var arr = []; for (var i = 0; i < 99; i++){ var someValue=getRandomInt(0,99); arr.push(someValue); } //shuffle(arr); for (var i = 0; i < 99; i++) document.writeln(arr[i]); // BINARY SEARCH function BinarySearch (SomeArray,Key){ var LowIndex=0; var HighIndex=SomeArray.length; //document.writeln('<br>'+HighIndex); var i=Math.floor( (LowIndex + HighIndex) / 2); while (LowIndex<=HighIndex) { if (SomeArray[i]=Key) break; if (SomeArray[i]>Key){HighIndex=i-1} else if (SomeArray[i]<Key){LowIndex=i+1} i=Math.floor( (LowIndex+HighIndex)/2); } if (LowIndex<=HighIndex){return i} else return-1; } var Result=BinarySearch(arr,'3'); alert(Result); </Script> </head> <body> </body> </html> |