Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Binary Search Recursive
//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 lowIndx = 0; int highIndx = nums.Length - 1; int findIndx = BinarySearchRec(nums,searchNum, lowIndx, highIndx); 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 BinarySearchRec(int[] nums, int searchNum, int lowIndx, int highIndx){ if (lowIndx > highIndx) { return -1; } else { int midIndx = (lowIndx + highIndx)/2; if (searchNum == nums[midIndx]) { return midIndx; } else if (searchNum < nums[midIndx]) { return BinarySearchRec(nums, searchNum, lowIndx, midIndx - 1); } else { return BinarySearchRec(nums, searchNum, midIndx + 1, highIndx); } } } public static int[] getList(){ int [] nums = { 2, 4, 6, 8, 10, 12 }; return nums; } } }
run
|
edit
|
history
|
help
0
1 through 1000
prime number
look at this, soaches
Math 10.81 added quad seq
Print 1 to 100 without using loop
MVC Learning
bitcount algo
trees with reverse polish notation
Linq - When using FirstOrDefault, make sure to check for null result
text