Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class BinarySearchAlgorithm
- {
- static void Main()
- {
- //Write a program that finds the index of given element in a sorted array of integers by using the binary search algorithm (find it in Wikipedia).
- int[] searchArray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
- Array.Sort(searchArray);
- int numToSearch = 8,
- startSearchIndex = 0,
- endSearchIndex = searchArray.Length-1,
- currentMiddle = 0;
- bool foundFlag = false;
- while (startSearchIndex <= endSearchIndex)
- {
- currentMiddle = (startSearchIndex + endSearchIndex)/2;
- if (searchArray[currentMiddle] == numToSearch)
- {
- Console.WriteLine("The index of the searched number {0} is: {1}", numToSearch, currentMiddle);
- foundFlag = true;
- break;
- }
- else if (searchArray[currentMiddle] < numToSearch)
- {
- startSearchIndex = currentMiddle + 1;
- }
- else
- {
- endSearchIndex = currentMiddle - 1;
- }
- }
- if (foundFlag == false)
- {
- Console.WriteLine("Number {0} not found in the array!", numToSearch);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement