
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Array.BinarySearch Method with Examples in C#
The Array.BinarySearch(Array, Object) method in C# is used to search an entire one-dimensional sorted array for a specific element, using the IComparable interface implemented by each element of the array and by the specified object.
Syntax
public static int BinarySearch (Array arr, object val);
Above, arr is the sorted 1-D array, whereas val is the object to search for.
Example
using System; public class Demo { public static void Main() { int[] intArr = {5, 10, 15, 20}; Array.Sort(intArr); Console.WriteLine("Array elements..."); foreach(int i in intArr) { Console.WriteLine(i); } Console.Write("Element 25 is at index = " + Array.BinarySearch(intArr, 20)); } }
Output
Array elements... 5 10 15 20 Element 25 is at index = 3
Example
using System; public class Demo { public static void Main() { string[] strArr = {"John", "Tim", "Fedric", "Gary", "Harry", "Damien"}; Array.Sort(strArr); Console.WriteLine("Array elements..."); foreach(string s in strArr) { Console.WriteLine(s); } Console.Write("Element Gary is at index = " + Array.BinarySearch(strArr, "Gary")); Console.Write("
Element Tom is at index = " + Array.BinarySearch(strArr, "Tom")); } }
Output
Array elements... Damien Fedric Gary Harry John Tim Element Gary is at index = 2 Element Tom is at index = -7
Advertisements