Created
May 5, 2021 15:15
-
-
Save jbollman7/664d6726d185a49db6e29c580de21215 to your computer and use it in GitHub Desktop.
Binary Search C#
This file contains hidden or 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; | |
namespace BinarySearch | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
int[] MyArray = new int[]{1,2,3,4,5,6,7}; | |
//Console.WriteLine(); | |
//BinarySearch(MyArray, 3); | |
int myAnswer = 5/2; | |
Console.WriteLine(myAnswer); | |
Array. | |
} | |
public static int BinarySearch(int[] array, int x) | |
{ | |
int p = 0; | |
int n = array.Length -1; | |
int r = n; | |
int TotalLoops = 1; | |
int q = 0; | |
if (x > array.Length -1) | |
throw new Exception(); | |
while (p <= r) | |
{ | |
Console.WriteLine($"Total times cycled through loop {TotalLoops}"); | |
if (q == q) | |
q = ((p+r) / 2) + 1; | |
else | |
q = (p+r) / 2; | |
Console.WriteLine($"Value for q is now {q}"); | |
if (TotalLoops > 5) | |
break; | |
if (x < array[q]) | |
{ | |
r = q - 1; | |
Console.WriteLine($"x is less than array[q] {x} is less than {array[q]}"); | |
Console.WriteLine($"Everything {array[q]} and above have now been eliminated from consideration"); | |
Console.WriteLine(" "); | |
TotalLoops++; | |
} | |
else if(x > array[q]) | |
{ | |
p = q; | |
Console.WriteLine($"x is more than array[q] {x} is more than {array[q]}"); | |
Console.WriteLine($"Everything {array[q]} and less have now been eliminated from consideration"); | |
Console.WriteLine(" "); | |
TotalLoops++; | |
} | |
else | |
{ | |
Console.WriteLine($"The value of array[q] matches x. {array[q]} == {x}"); | |
Console.WriteLine($"X has been found"); | |
return 0; | |
} | |
} | |
return -1; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment