📒
Notes
Cloud ComputingData Science/AIGame Development
  • Home
  • Big O
  • Data Structures & Algorithms
    • Data Structures
      • Array
      • Stack
      • Queue
      • Linked List
      • Binary Tree
    • Algorithms
      • Searching
      • Sorting
      • Graphs
        • Searching
        • Minimum Spanning Tree
        • Shortest Path Algorithms
      • String Algorithms
  • Object Oriented Programming
  • Languages
    • HTML/CSS
      • CSS
    • C++
    • C#
      • Types
      • Keywords
        • Modifiers
          • Access Modifiers
        • Method Parameters
      • Operators and Expressions
      • Collections
      • Constructors
      • Delegates
      • Indexers
      • Concepts
      • Features
        • LINQ
          • Operators
          • Working with Data
          • Methods
          • Resources
        • Asynchronous Programming
        • Reflection
    • Dart
    • GraphQL
    • JavaScript
      • Variable and Parameter
      • Built-in objects
        • Array
        • Built-in Functions
      • Functions
      • Classes
      • Prototype
      • Libraries
        • jQuery
        • React
          • Components
          • State and Lifecycle
          • Hooks
            • useState
            • useEffect
          • Resources
      • Testing Framework
      • Web APIs
    • Kotlin
      • Basics
    • Python
      • Basics
      • Data Structures
      • Functions
      • Resources
        • Flask
    • SQL
      • Basics
      • Operators
      • JOINs
      • Aggregations
      • Subqueries
      • Views
      • Functions
        • Window Functions
      • Stored Procedures
      • Performance Tuning
      • Extras
    • Resources
  • 🌐Web Frameworks
    • Angular
      • Templates
      • Directives
        • Attribute Directives
        • Structural Directives
    • ASP.NET
      • Fundamentals
        • Dependency Injection
        • Middleware
        • Session & State Management
      • Web apps
        • MVC
          • Controllers
            • Filters
          • Models
            • Model Binding
            • Model Validation
          • Views
            • Tag Helpers
            • View Components
          • Features
        • Client-side development
      • Web APIs
        • Controller-based APIs
        • Minimal APIs
        • OpenAPI
        • Content Negotiation
      • SignalR
      • Host and Deploy
        • IIS
      • Security
    • Django
      • The Request/Response Cycle
    • Terminologies
      • Web Server
        • Internet Information Services
    • Resources
  • 📱App Frameworks
    • Introduction
      • Resources
    • Xamarin
      • Lifecycle
      • Custom Renderers & Effects
      • Behaviors
      • Triggers
      • Gestures
      • Commands
      • Dependency Service in XF
      • Libraries
      • Showcase
    • .NET MAUI
      • Controls
      • Navigation
      • Storage Options
  • Multi-Platform Frameworks
    • .NET
      • .NET Framework
        • ADO.NET
        • WCF
      • Fundamentals
        • Logging
        • Testing
      • Advanced
        • Asynchronous Programming
        • Parallel Programming
        • Threading
        • Memory Management
          • Garbage Collection
    • Flutter
  • Object-Relational Mappers
    • Entity Framework
      • Application Models
      • Configuration
      • Setting Up
      • Advanced
  • Databases
    • Introduction
      • DBMS Architecture
      • Normalization
      • Database Transaction Models
    • Relational Databases
      • Microsoft SQL Server
        • Basics
        • Functions
        • Stored Procedures
        • Error Handling
        • Log Shipping
        • Querying and Manipulating JSON data
        • Statements
        • Topics
        • Extras
    • Non-Relational Databases
      • MongoDB
      • Redis
        • Data Structures
        • Introduction
        • Managing Database
  • Tools
    • Version Control
      • Git
        • Setup and Config
        • Basics
          • Sharing and Updating Projects
        • Resources
      • Perforce Helix
    • GitHub
    • Powershell
  • Software Development
    • Software Development Life Cycle
    • Software Design Patterns
      • GoF Design Patterns
      • Architectural Patterns
        • MVC
        • MVVM
        • N-tier Architecture
        • Onion Architecture
        • Data Transfer Objects
      • CQRS
    • Software Design Principles
      • S.O.L.I.D. Priniciple
  • System Design
    • Topics
      • Load Balancing
  • Topics
    • JWT
    • Caching
      • Static vs Dynamic Caching
    • OSI model
      • HTTP
    • Glossary
    • API
      • SOAP
      • REST
    • Microservices
    • WebHooks
    • Practice
    • Operating Systems
      • Windows
    • Architecture
  • 🔖Bookmarks
  • 🔗Resources
Powered by GitBook
On this page
  • Linear Search
  • Binary Search

Was this helpful?

  1. Data Structures & Algorithms
  2. Algorithms

Searching

PreviousAlgorithmsNextSorting

Last updated 2 years ago

Was this helpful?

Linear Search

int? LinearSearch(int[] array, int target){
    int n = array.Length - 1;
    for(int i = 0; i <= n; i++){
        if(array[i] == target)
            return i;
    }
    return -1;
}
def linear_search(array, target):
    for i in range(0, len(array)):
        if (array[i] == target):
            return i
    return -1

Time Complexity: O(n)

Binary Search

  • Binary search works only on a sorted set of elements.

int? BinarySearch(int[] array, int target){
    var startIdx = 0;
    var endIdx = array.Length - 1;
    while(startIdx <= endIdx){
        var middleIdx = (startIdx + endIdx) / 2;
        var middleItem = array[middleIdx];
        if(target < middleItem)
            endIdx = middleIdx - 1;
        else if(target > middleItem)
            startIdx = middleIdx + 1;
        else
            return middleIdx;
    }
    return -1;
}
  • Using Recursion:

int? RecursiveBinarySearch(int[] array, int target, int low, int high){
    if(low > high)
        return -1;
    
    var middleIdx = (low + high) / 2;
    var middleItem = array[middleIdx];
    if(target < middleItem)
        return RecursiveBinarySearch(array, target, low, middleIdx - 1);
    else if(target > middleItem)
        return RecursiveBinarySearch(array, target, middleIdx + 1, high);
    else
        return middleIdx;
}
  • Using Recursion

def rec_binary_search(array, target, low, high):
    if high >= low:
        mid = low + (high - low) // 2
        if target < array[mid]:
            return rec_binary_search(array, target, low, mid-1) # left half
        elif target > array[mid]:                                   
            return rec_binary_search(array, target, mid + 1, high) # right half
        else:                                                       
            return mid
    else:
        return -1

Time Complexity: O(log n)

Fact

If all the names in the world are written down together in order and you want to search for the position of a specific name, binary search will accomplish this in a maximum of 35 iterations.

Linear Search < Binary Search

Linear/Sequential Search
Binary Search