ค้นหาจากตำแหน่งกึ่งกลาง ถ้าเจอก็จบ
ถ้าไม่เจอ แล้วเลขที่ค้นหามีค่ามากกว่า ก็หาต่อทางครึ่งซ้าย
ถ้าไม่เจอ แล้วเลขที่ค้นหามีค่าน้อยกว่า ก็หาต่อทางครึ่งขวา
โค๊ด
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 |
using System; namespace ConsoleApp1 { class Program { static void Main(string[] args) { // declare an array of integers that will be used for searching int[] arrLinearSearch = { 2, 3, 4, 5, 8, 10 }; int searchTerm = 8; int result = BinarySearch(arrLinearSearch, searchTerm, 0, arrLinearSearch.Length - 1); if (result != -1) { Console.WriteLine($"Search term found at index {result}."); } else { Console.WriteLine("Search term not found in the array."); } } public static int BinarySearch(int[] arr, int key, int first, int last) { while (first <= last) { int mid = (first + last) / 2; if (key == arr[mid]) { return mid; } else if (key < arr[mid]) { last = mid - 1; } else { first = mid + 1; } } return -1; } } } |
ผลการรัน
[code]
Search term found at index 4.
Press any key to continue . . .
[/code]