Searching - PowerPoint PPT Presentation

1 / 6
About This Presentation
Title:

Searching

Description:

Stop if key is found or an item with larger value is reached or end is ... x within the range first, ..., last, and index = -1 if key is not in this range of x ... – PowerPoint PPT presentation

Number of Views:19
Avg rating:3.0/5.0
Slides: 7
Provided by: IRE62
Category:
Tags: index1 | searching

less

Transcript and Presenter's Notes

Title: Searching


1
Searching
  • Irena Pevac
  • CS501

2
Searching
  • Searching for key in an unordered array
  • Sequential search
  • Compare key with every item
  • Stop if key is found or end is reached
  • Searching for key in an ordered array
  • Sequential search
  • Compare key with every item
  • Stop if key is found or an item with larger value
    is reached or end is reached
  • Binary search
  • Compare key with item in the middle
  • Search further in appropriate half of the array

3
Linear Search
  • int seqSearch(int x, int n, int key)
  • for (int index 0 index lt n index)
  • if (key xindex)
  • return index // Success!
  • return -1

4
Linear Search in ordered array
  • int linearSearchOrdered (int x, int n, int
    key)
  • for (int index 0 index lt n index)
  • if (key xindex)
  • return index // key found
  • else if (key lt xindex)
  • return -1 // no need to search
    further
  • return -1

5
Binary Search
  • Input array x, first, last, and key, all
    integers, where x is an ordered array in the
    range first, , last, and key is the item sought.
  • Output index such that xindex key if key is
    in x within the range first, , last, and index
    -1 if key is not in this range of x

6
  • Binary Search
  • int binarySearch(int x, int first, int last,
    int key)
  • if (last lt first)
  • index -1
  • else
  • int mid (first last)/2
  • if (key xmid)
  • index mid
  • else if (key lt xmid)
  • index binarySearch(x, first,
    mid-1, key)
  • else
  • index binarySearch(x, mid1, last,
    key)
  • return index
Write a Comment
User Comments (0)
About PowerShow.com