Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Binary search iterative approach
//Rextester.Program.Main is the entry point for your code. Don't change it. //Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5 using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Rextester { public class Program { public static void Main(string[] args) { //Your code goes here Console.WriteLine("-------- Binary search --------"); // Binary search: the data collection should be in the sorted form. // Binary search looks for a particular item by comparing the middle most item of the collection. // If a match occurs, then the index of item is returned. If the middle item is greater than the item, // then the item is searched in the sub-array to the left of the middle item. Otherwise, // the item is searched for in the sub-array to the right of the middle item. // This process continues on the sub-array as well until the size of the subarray reduces to zero. int[] nums = getList(); int searchNum = 4; int findIndx = BinarySearch(nums,searchNum); if(findIndx >= 0) { Console.WriteLine("Binary search successful"); Console.WriteLine("Number {0} found at index {1} and at Location {2}", searchNum, findIndx, findIndx + 1); } else { Console.WriteLine("NOT FOUND"); } } public static int BinarySearch(int[] nums, int searchNum){ int lowIndx = 0; int highIndx = nums.Length - 1; while (lowIndx <= highIndx) { int midIndx = (lowIndx + highIndx) / 2; if (searchNum < nums[midIndx]) { highIndx = midIndx - 1; } else if (searchNum > nums[midIndx]) { lowIndx = midIndx + 1; } else if (searchNum == nums[midIndx]) { return midIndx; } } return -1; } public static int[] getList(){ int [] nums = { 2, 4, 6, 8, 10, 12 }; return nums; } } }
run
|
edit
|
history
|
help
0
ArithmeticOperations
d
megha
Split string into equal chunks
sktieritjre
circleTest
factorial ncr
Work Days
Public access specifier
Greatest Common Divisor of 2 or more numbers.