using System;
namespace MyCompiler {
class Program {
public static void Main(string[] args) {
int[] myArr = {5,7,7,8,8,10};
int target = 8;
int[] ans = binarySearch(myArr,target);
Console.WriteLine("Element found at index: ["+ ans[0] + "," + ans[1]+"]");
}
static int[] binarySearch(int[] arr,int target){
int[] ans = {-1,-1};
//Check fisrt occurance if target first
int start = searchNumberIndex(arr,target,true);
int end = searchNumberIndex(arr,target,false);
ans[0] = start;
ans[1] = end;
return ans;
}
static int searchNumberIndex(int[] arr,int target,bool forStartIndex){
int ans = -1;
int start = 0;
int end = arr.Length - 1;
while(start<=end){
int middle = start + (end-start)/2;
if(target < arr[middle]){
end = middle - 1;
}else if(target > arr[middle]){
start = middle + 1;
}else{
ans = middle;
if(forStartIndex){
end = middle -1;
}else{
start = middle+1;
}
}
}
return ans;
}
}
}
To embed this project on your website, copy the following code and paste it into your website's HTML: