chore(CSharp): adding binary-search (#307)

Co-authored-by: sonu-dev <sonu.concious@gmail.com>
pull/310/head
Sonu Thakur 2021-05-16 22:05:57 +05:30 committed by GitHub
parent ada02c2b40
commit 5205a67343
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 108 additions and 0 deletions

View File

@ -9,3 +9,6 @@ For running the `.cs` file please using [.Net Finddle](https://dotnetfiddle.net/
## Strings
- [Palindrome](src/Strings/palindrome.cs)
## Search
- [Binary Search](src/Search/binary-search.cs)

View File

@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Algorithms.Search
{
public class BinarySearch
{
public static void Main()
{
var sortedArray = new int[] { 2, 4, 7, 9, 23 };
var item = 9;
var resultIndex = Search(sortedArray, item);
if (resultIndex != -1)
{
Console.WriteLine($"item {item} found at index {resultIndex} into array");
}
else
{
Console.WriteLine($"item {item} not found into array");
}
}
///Prerequisite: Array must be sorted
//Returns index of item if it is present in sorted array, else return -1
public static int Search(int[] sortedArr, int item)
{
var arrLength = sortedArr.Length;
if (arrLength == 0)
{
return -1;
}
var left = 0;
var right = arrLength -1;
while (left <= right)
{
var mid = (left + right) / 2;
if (item == sortedArr[mid])
{
return mid;
}
if (item < sortedArr[mid])
{
right = mid - 1;
}
else
{
left = mid + 1;
}
}
return -1;
}
public static int BuiltInBinarySearch(List<int> input, int item)
{
var sortedList = input.OrderBy(x => x).ToList();
var index = sortedList.BinarySearch(item);
return index < 0 ? -1 : index;
}
}
}

View File

@ -0,0 +1,40 @@
using Algorithms.Search;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Algorithms.Tests.Search
{
[TestFixture]
public class BinarySearchTest
{
[TestCase(new int[]{ 1,2,3,4,5}, 4)]
public void BinarySearch_GetIndexOfItem(int[] input, int item)
{
var expected1 = BinarySearch.Search(input, item);
Assert.AreEqual(expected1, 3);
}
[TestCase(new int[] { 10, 21, 34, 46, 57, 68 }, 59)]
public void BinarySearch_ItemNotFound(int[] input, int item)
{
var expected = BinarySearch.Search(input, item);
Assert.AreEqual(expected, -1);
}
[TestCase(new int[] { 1, 2, 3, 4, 5 }, 4)]
public void BuildInBinarySearch_GetIndexOfItem(int[] input, int item)
{
var expected = BinarySearch.BuiltInBinarySearch(input.ToList(), item);
Assert.AreEqual(expected, 3);
}
[TestCase(new int[] { 1, 2, 3, 4, 5 }, 8)]
public void BuildInBinarySearch_ItemNotFound(int[] input, int item)
{
var expected = BinarySearch.BuiltInBinarySearch(input.ToList(), item);
Assert.AreEqual(expected, -1);
}
}
}