Skip to content

Commit 799cef0

Browse files
committed
Added Binary Search in C#
1 parent e2e75a0 commit 799cef0

1 file changed

Lines changed: 58 additions & 0 deletions

File tree

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
namespace BinarySearch{
6+
7+
//Implementation of Binary Search Algorithm
8+
//links: http://en.wikipedia.org/wiki/Binary_search_algorithm
9+
10+
//This algorithm expects the Passed array is already sorted
11+
// Array.Sort(array); can be used to sort the array if necessary
12+
// before passing the array to the search functions
13+
class BinarySearch{
14+
15+
public static int search(int [] arr, int target){
16+
17+
int low=0;
18+
int high= arr.Length;
19+
20+
while(low<high){
21+
22+
int mid=(int)((low+high)/2);
23+
24+
if(arr[mid]==target){
25+
return mid;
26+
27+
}
28+
else if(arr[mid]>target) {
29+
30+
high=mid-1;
31+
}
32+
else{
33+
34+
low=mid+1;
35+
}
36+
}
37+
return high;
38+
39+
40+
41+
}
42+
43+
44+
}
45+
46+
class Test{
47+
48+
static void Main(string[] args){
49+
50+
int [] test={1,2,3,4,5,6,7,8,9};
51+
int index;
52+
53+
index=BinarySearch.search(test,7);
54+
if(test[index]==7)Console.WriteLine("Test Successful");
55+
56+
}
57+
}
58+
}

0 commit comments

Comments
 (0)