-2

NOTE: Assignment help, No code required.

I have a list of file names in a list-box. As part of the assignment I want to search the file names using a binary search implementation.

Can someone help me understand how to implement a binary search without using the built-in List<T>.BinarySearch(...) method?

Paul Turner
  • 38,949
  • 15
  • 102
  • 166
Kevin Chun
  • 31
  • 6
  • what u want to do with searched file? Do you need the file index or name? – andy Mar 05 '13 at 11:34
  • Is there anything that you've tried? – Tim Schmelter Mar 05 '13 at 11:34
  • do binary search without doing binary search? I don't get it :) – TravellingGeek Mar 05 '13 at 11:35
  • +1 for noting about assignment help. – webnoob Mar 05 '13 at 11:36
  • Check: http://www.youtube.com/watch?v=wNVCJj642n4 – Petrutiu Mihai Mar 05 '13 at 11:36
  • @GeraldSv: I assume that he's trying to reimplement [`Array.BinarySearch Method`](http://msdn.microsoft.com/en-us/library/system.array.binarysearch(v=vs.110).aspx) – Tim Schmelter Mar 05 '13 at 11:36
  • Yeah the assignment requires us to create a binary search method, which were not allowed to use the C# List.BinarySearch function – Kevin Chun Mar 05 '13 at 11:38
  • Note: Presume the lsit is already sorted – Kevin Chun Mar 05 '13 at 11:39
  • @TimSchmelter I can only find information about C# List.BinarySearch function. Ive tried looking through text books but nothing – Kevin Chun Mar 05 '13 at 11:40
  • @KevinChun: You can have a look at the implementation with `ILSpy`, you'll find it in `ArraySortHelper`(note that `List.BinarySearch` also uses [`Array.BinarySearch`](http://msdn.microsoft.com/en-us/library/system.array.binarysearch(v=vs.110).aspx)). But _"binary search is surprisingly hard to write correctly"_ http://stackoverflow.com/a/3256430/284240 – Tim Schmelter Mar 05 '13 at 11:45
  • @TimSchmelter: haha. yeah i thought so. I might just use the .BinarySearch and lose some marks, I havent had much practice with C# programming so i might not be able to implement the method of that complexity into my assignment – Kevin Chun Mar 05 '13 at 11:58

1 Answers1

1

You have to begin with a sorted list of values. Then you just search like you would if you were playing a number guessing game (and were a computer). Pick the middle element of your list. If the number you're searching for isn't equal to the value of the middle element, do the same thing again, but this time on a sub-list that's half the size (since the list is sorted, you know what side of the list your target is on). Just keep doing that until you found the value you're looking for.

Memento Mori
  • 3,327
  • 2
  • 22
  • 29