Created
September 8, 2014 01:40
-
-
Save ajinkyakulkarni/fc9cecbf48b38de8771b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Text; | |
namespace BinarySearch | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
int[] A = { 1, 2, 3, 4, 5, 6 ,7,8,9}; | |
int K = 9; //item to search | |
int pos=BinarySearch(A, K); | |
if(pos==-1){ | |
Console.WriteLine("Item "+ K + " not found"); | |
}else{ | |
Console.WriteLine("Item "+ K + " found at " + pos); | |
} | |
Console.ReadLine(); | |
} | |
static int BinarySearch(int[] A, int K) | |
{ | |
int n = A.Length; | |
int l = 0; | |
int r = n - 1; | |
while (l <= r) | |
{ | |
int m = ((l + r) / 2); | |
if (K == A[m]) | |
{ | |
return m; | |
} | |
else if (K < A[m]) | |
{ | |
r = m - 1; | |
} | |
else | |
{ | |
l = m + 1; | |
} | |
} | |
return -1; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment