using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BinarySearchTest
{
public static class BinarySearch
{
public static Dictionary<int, int> BinarySearchToFindElementWithIndex(int[] array, int findElement)
{
Dictionary<int, int> dictionary = new Dictionary<int, int>(){ };
int startIndex = 0; int midIndex = 0;
int endIndex = array.Length - 1;
while (startIndex <= endIndex)
{
midIndex = (startIndex + endIndex) / 2;
if (array[midIndex] > findElement)
{
endIndex = midIndex - 1;
}
else if (array[midIndex] < findElement)
{
startIndex = midIndex + 1;
}
else if (array[midIndex] == findElement)
{
dictionary.Add(midIndex, findElement);
break;
}
}
return dictionary;
}
}
class Program
{
static void Main(string[] args)
{
int[] array = { 1, 2, 3, 4, 5, 6, 10, 12, 20 };
Dictionary<int,int> findElement = BinarySearch.BinarySearchToFindElementWithIndex(array,12);
foreach (var item in findElement)
{
Console.WriteLine("Find element {0} at index {1}",item.Value, item.Key);
}
Console.ReadLine();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BinarySearchTest
{
public static class BinarySearch
{
public static Dictionary<int, int> BinarySearchToFindElementWithIndex(int[] array, int findElement)
{
Dictionary<int, int> dictionary = new Dictionary<int, int>(){ };
int startIndex = 0; int midIndex = 0;
int endIndex = array.Length - 1;
while (startIndex <= endIndex)
{
midIndex = (startIndex + endIndex) / 2;
if (array[midIndex] > findElement)
{
endIndex = midIndex - 1;
}
else if (array[midIndex] < findElement)
{
startIndex = midIndex + 1;
}
else if (array[midIndex] == findElement)
{
dictionary.Add(midIndex, findElement);
break;
}
}
return dictionary;
}
}
class Program
{
static void Main(string[] args)
{
int[] array = { 1, 2, 3, 4, 5, 6, 10, 12, 20 };
Dictionary<int,int> findElement = BinarySearch.BinarySearchToFindElementWithIndex(array,12);
foreach (var item in findElement)
{
Console.WriteLine("Find element {0} at index {1}",item.Value, item.Key);
}
Console.ReadLine();
}
}
}
No comments:
Post a Comment