
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
Binary search in C#
Binary search works on a sorted array. The value is compared with the middle element of the array. If equality is not found, then the half part is eliminated in which the value is not there. In the same way, the other half part is searched.
Here is the mid element in our array. Let’s say we need to find 62, then the left part would be eliminated and the right part is then searched −
These are the complexities of a binary search −
Worst-case performance | O(log n) |
Best-case performance | O(1) |
Average performance | O(log n) |
Worst-case space complexity | O(1) |
Example
Let us see the method to implement the binary search −
public static object BinarySearchDisplay(int[] arr, int key) { int minNum = 0; int maxNum = arr.Length - 1; while (minNum <=maxNum) { int mid = (minNum + maxNum) / 2; if (key == arr[mid]) { return ++mid; } else if (key < arr[mid]) { max = mid - 1; }else { min = mid + 1; } } return "None"; }
- Related Articles
- Binary Search in C++
- Binary Search in C++ program?
- Binary Search Tree - Search and Insertion Operations in C++
- Binary Search functions in C++ STL
- Binary Search Tree Iterator in C++
- Unique Binary Search Trees in C++
- Binary Search a String in C++
- Explain Binary search in C language
- Recover Binary Search Tree in C++
- Binary Tree to Binary Search Tree Conversion in C++
- Binary Search using pthread in C Program?
- Balance a Binary Search Tree in c++
- Binary Search Tree - Delete Operation in C++
- Unique Binary Search Trees II in C++
- Binary Search in C++ Standard Template Library (STL)

Advertisements