Docsity

LECTURE 06: SEARCHING ALGORITHMS, Lecture notes of Data Structures and Algorithms

Toggle sidebar
bg1
Data Structures and
Algorithms
LECTURE 06: SEARCHING ALGORITHMS
pf3
pf4
pf5
pf8

Partial preview of the text

Download LECTURE 06: SEARCHING ALGORITHMS and more Lecture notes Data Structures and Algorithms in PDF only on Docsity!

Data Structures and Algorithms LECTURE 06: SEARCHING ALGORITHMS

  • Searching Algorithms
    • Linear Search
    • Binary Search Contents
  • Linear search finds a particular value in a list
    • Checking every one of the elements
    • One at a time, in sequence
    • Until the desired one is found
  • Worst & average performance: O(n)
  • See the visualization Linear Search for each item in the list: if that item has the desired value, return the item's location return nothing

Linear Search int LinearSearch(int arr[], int x) { int n = arr.length; for (int i = 0; i < n; i++) { if (arr[i] == x) return i; } return -1; }

Binary Search (Iterative) int binarySearch(int arr[], int key, int start, int end) { while (end >= start) { int mid = (start + end) / 2; if (arr[mid] < key) start = mid + 1; else if (arr[mid] > key) end = mid - 1; else return mid; } return KEY_NOT_FOUND; }

Searching algorithms  Binary Search, Linear Search Summary