1 / 14

Search and Recursion

Search and Recursion. CS221 – 2/23/09. List Search Algorithms. Linear Search: Simple search through unsorted data. Time complexity = O(n ) Binary Search: Fast search through sorted data. Time complexity = O(log n ). How to Choose?. Linear search is optimal for Unsorted data

carys
Télécharger la présentation

Search and Recursion

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Search and Recursion CS221 – 2/23/09

  2. List Search Algorithms • Linear Search: Simple search through unsorted data. Time complexity = O(n) • Binary Search: Fast search through sorted data. Time complexity = O(logn)

  3. How to Choose? • Linear search is optimal for • Unsorted data • Small data sets • Data sets that will change often between searches • Binary search is optimal for • Sorted data • Large data sets where performance is important • Data sets that are relatively stable

  4. How to Implement Linear Search • Take a data-set to search and a key to search for • Iterate through the data set • Test each item to see if it equals your key • If it does, return true • If you exit the iteration without the item, return false

  5. Integer Linear Search

  6. Search Keys • Generally, search key and search result are not the same • Consider: • Search for a business by address • Search for a passenger by last name • Search for a bank account by social security #

  7. Search Keys • How would the search change if the key is not the result?

  8. Generic Linear Search

  9. How to Implement Binary Search • Take a sorted data-set to search and a key to search for • Start at the mid-point and see if that’s the key • If not, see if you need to search above or below the mid-point • Pick halfway point above or below and test again • Repeat until you can no longer cut the remaining set in half

  10. Binary Search

  11. Binary Search

  12. How to Implement Binary Search • Given a sorted array and a key • First = start of list • Mid = middle of list • Last = end of list • if array[mid] == key • Return key • If mid > key • Last = mid - 1 • If mid < key • First = mid + 1 • Mid = (first + last)/2 • Continue until first > last • If the key isn’t found, throw an exception

  13. Integer Binary Search

  14. Generic Binary Search

More Related