Skip to main content
Ctrl+K
Logo image
  • CSC-122 Data Structures & Algorithms (Spring 2024)
  • Calendar
  • Syllabus
    • Purposeful Pathways (Spring ‘24)
    • Grading
    • Textbooks & Other Resources
    • Mental Health Resources
    • Center for Academic Success
    • Accomodations
    • Academic Integrity
    • Nondiscrimination Policy and Sexual Misconduct
  • Introduction

Designing Abstract Processes (Algorithms)

  • 1. Analysis
    • 1.4. Time Complexity
    • 1.5. Space Complexity
  • 2. Brute Force
    • 2.1. Linear Search
    • 2.2. Bogosort
  • 3. Decrease and Conquer
    • 3.1. Selection Sort
    • 3.2. Insertion Sort
  • 4. Divide and Conquer
    • 4.1. Binary Search
    • 4.2. Merge Sort
    • 4.3. Quick Sort
  • 5. Recursion
    • 5.4. Linear Recursion
    • 5.5. Tree Recursion

Building Abstractions with Data (Data Structures)

  • 6. Object-Oriented Programming
    • 6.1. Native Data Types
    • 6.2. User-defined Types
    • 6.3. Extending Types
    • 6.4. Extending Operators
  • 7. Stacks and Queues
    • 7.1. Stacks
    • 7.2. Queues
  • 8. Linked Lists
    • 8.1. Singly Linked Lists
    • 8.2. Doubly Linked Lists
    • 8.3. Circular Linked Lists
  • 9. Arrays (under the hood)
  • 10. Files and Modules
  • Repository
  • Open issue
  • .md

Linear Search

Contents

  • 2.1.1. Analysis

2.1. Linear Search#

Linear Search (also known as Sequential Search) is a brute force search algorithm that finds a target value within a list by sequentially checking each element of the list until a match is found.



The pseudocode for the algorithm is as follows:

Algorithm 2.1 (Linear Search Algorithm)

Inputs Given a list of numbers \(L\) of length \(n\) and a target value \(t\)

Output The index of the target value \(t\) in the list \(L\) of length \(n\)

  1. For \(i\) from \(0\) to \(n-1\):

    1.1. If \(L[i] == t\):
    1.1.1. Return \(i\)
    1.2. end If

  2. end For

  3. Return -1

Python implementation of the algorithm is as follows:

data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
query = 5

def linear_search(data, query):
    """
    Returns the index position of the target if found, else returns -1
    """
    i = 0
    while i < len(data):
        if data[i] == query:
            return i
    return -1

linear_search(data, query)

2.1.1. Analysis#

The time complexity of the above algorithm is O(n) since in the worst case we have to iterate over the entire list to find the target.

In best case, the target is found at the first index, thus the best case is O(1).

Assuming uniform distribution of the target value, the average case is If each element is equally likely to be searched, then linear search has an average case of \( \frac{n+1}{2}\) comparisons. Thus, the average case is O(n).

The space complexity of the above algorithm is O(1) since we are not using any extra space.

previous

2. Brute Force

next

2.2. Bogosort

Contents
  • 2.1.1. Analysis

By Syed Fahad Sultan

© Copyright 2022.