Last active
December 12, 2015 01:18
-
-
Save jonnyli1125/4689902 to your computer and use it in GitHub Desktop.
A little test of using a binary search algorithm to find indexes of values in a sorted list. Also just a little comparison between binary and linear/sequential searching.
This file contains 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; | |
using System.Collections.Generic; | |
namespace BinarySearch | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
List<int> list = new List<int>() { 5, 8, 900, 1, 22, 52, 567, 666, 123, 256, 765, 0, 500 }; // example list | |
int search = 666; // the value to find the index of | |
list.Sort(); // sorts list | |
int low = 0, high = list.Count, mid = 0, prevmid = 0, counter = 0; // declare low, high, middle, previousmiddle, and counter variables | |
while (search != list[mid]) // binary searching algorithm | |
{ | |
mid = (low + high) / 2; // middle point (average) | |
if (mid == prevmid) { Console.WriteLine("Impossible to find."); Console.Read(); return; } // if prevmid and mid are equal (meaning the calculation was exact same as last time), we don't want to stay in this infinite loop that we can't get a result from, so break/return | |
prevmid = mid; // assign mid to prevmid | |
if (list[mid] > search) high = mid; // cut out everything from mid and above | |
else low = mid; // cut out everything from mid and below | |
counter++; // increment number of steps taken | |
} | |
// output results | |
Console.WriteLine("list = {" + String.Join(",", list.ConvertAll<string>(i => { return i.ToString(); })) + "}"); | |
Console.WriteLine("list[" + mid + "] = " + list[mid]); | |
Console.WriteLine("Using a binary search algorithm, " + counter + " steps are taken to solve this calculation."); | |
Console.WriteLine("Using a linear/sequential search algorithm, " + mid + " steps are taken to solve this calculation."); | |
Console.Read(); | |
} | |
} | |
} |
I don't know how Microsoft does it, but I'd assume maybe something like this: http://pastie.org/6006391
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How long does it take to sort the list?