Computer Science 111 Fundamentals of Programming I Search Algorithms.

Slides:



Advertisements
Similar presentations
College of Information Technology & Design
Advertisements

Searching for Data Relationship between searching and sorting Simple linear searching Linear searching of sorted data Searching for string or numeric data.
CSE Lecture 3 – Algorithms I
Efficiency of Algorithms Csci 107 Lecture 6-7. Topics –Data cleanup algorithms Copy-over, shuffle-left, converging pointers –Efficiency of data cleanup.
Fundamentals of Python: From First Programs Through Data Structures
Searching Kruse and Ryba Ch and 9.6. Problem: Search We are given a list of records. Each record has an associated key. Give efficient algorithm.
Conditional Statements Introduction to Computing Science and Programming I.
Search and Recursion CS221 – 2/23/09. List Search Algorithms Linear Search: Simple search through unsorted data. Time complexity = O(n) Binary Search:
Scott Grissom, copyright 2004 Chapter 5 Slide 1 Analysis of Algorithms (Ch 5) Chapter 5 focuses on: algorithm analysis searching algorithms sorting algorithms.
Efficiency of Algorithms February 11th. Efficiency of an algorithm worst case efficiency is the maximum number of steps that an algorithm can take for.
Searching Arrays Linear search Binary search small arrays
Searching Chapter Chapter Contents The Problem Searching an Unsorted Array Iterative Sequential Search Recursive Sequential Search Efficiency of.
©Silberschatz, Korth and Sudarshan14.1Database System Concepts 3 rd Edition Chapter 14: Query Optimization Overview Catalog Information for Cost Estimation.
Searching1 Searching The truth is out there.... searching2 Serial Search Brute force algorithm: examine each array item sequentially until either: –the.
1 Search Algorithms Sequential Search (Linear Search) Binary Search Rizwan Rehman Centre for Computer Studies Dibrugarh University.
CHAPTER 7: SORTING & SEARCHING Introduction to Computer Science Using Ruby (c) Ophir Frieder at al 2012.
Chapter 8 ARRAYS Continued
Python Control of Flow.
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Invitation to Computer Science, Java Version, Second Edition.
Computer Science 101 Fast Searching and Sorting. Improving Efficiency We got a better best case by tweaking the selection sort and the bubble sort We.
Data Structures & Algorithms CHAPTER 4 Searching Ms. Manal Al-Asmari.
 Pearson Education, Inc. All rights reserved Searching and Sorting.
SEARCHING. Vocabulary List A collection of heterogeneous data (values can be different types) Dynamic in size Array A collection of homogenous data (values.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Searching Course Lecture Slides 28 May 2010 “ Some things Man was never.
Searching. Linear (Sequential) Search Search an array or list by checking items one at a time. Linear search is usually very simple to implement, and.
CSCI 130 Array Searching. Methods of searching arrays Linear –sequential - one at the time –set does not have to be ordered Binary –continuously cutting.
CSC 211 Data Structures Lecture 13
Data Structures Using C++ 2E Chapter 9 Searching and Hashing Algorithms.
Computer Science 112 Fundamentals of Programming II Binary Search Trees.
Computer Science 101 Introduction to Sorting. Sorting One of the most common activities of a computer is sorting data Arrange data into numerical or alphabetical.
1 Section 2.1 Algorithms. 2 Algorithm A finite set of precise instructions for performing a computation or for solving a problem.
CHAPTER 8 SEARCHING CSEB324 DATA STRUCTURES & ALGORITHM.
Chapter 9 slide 1 Introduction to Search Algorithms Search: locate an item in a list (array, vector, table, etc.) of information Two algorithms (methods):
Bubble Sort.
Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions.
Sorting and Searching by Dr P.Padmanabham Professor (CSE)&Director
Computer Science 101 Fast Algorithms. What Is Really Fast? n O(log 2 n) O(n) O(n 2 )O(2 n )
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
Chapter 9 Sorting. The efficiency of data handling can often be increased if the data are sorted according to some criteria of order. The first step is.
Data Structures and Algorithms Searching Algorithms M. B. Fayek CUFE 2006.
Computer Science 112 Fundamentals of Programming II Searching, Sorting, and Complexity Analysis.
1. Searching The basic characteristics of any searching algorithm is that searching should be efficient, it should have less number of computations involved.
Searching Topics Sequential Search Binary Search.
8. DECISION STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Hossain Shahriar Announcement and reminder! Tentative date for final exam shown below, please choose a time slot! December 19.
Copyright © 2014 Curt Hill Algorithms From the Mathematical Perspective.
Sorting & Searching Geletaw S (MSC, MCITP). Objectives At the end of this session the students should be able to: – Design and implement the following.
Control Flow (Python) Dr. José M. Reyes Álamo. 2 Control Flow Sequential statements Decision statements Repetition statements (loops)
Control Flow (Python) Dr. José M. Reyes Álamo. 2 Control Flow Sequential statements Decision statements Repetition statements (loops)
CMPT 120 Topic: Searching – Part 2 and Intro to Time Complexity (Algorithm Analysis)
Chapter 3 Chapter Summary  Algorithms o Example Algorithms searching for an element in a list sorting a list so its elements are in some prescribed.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
1 compares each element of the array with the search key. works well for small arrays or for unsorted arrays works for any table slow can put more commonly.
Copyright Prentice Hall Modified by Sana odeh, NYU
Searching and Sorting Searching algorithms with simple arrays
16 Searching and Sorting.
Control Flow (Python) Dr. José M. Reyes Álamo.
Searching Given a collection and an element (key) to find… Output
Making Choices with if Statements
Python: Control Structures
Computer Science 112 Fundamentals of Programming II
CMPT 120 Topic: Searching – Part 1
Fundamentals of Programming II Binary Search Trees
Teach A level Computing: Algorithms and Data Structures
CSc 110, Spring 2017 Lecture 39: searching.
Winter 2018 CISC101 12/2/2018 CISC101 Reminders
MSIS 655 Advanced Business Applications Programming
Computer Science 111 Fundamentals of Programming I
The Binary Search by Mr. Dave Clausen
Presentation transcript:

Computer Science 111 Fundamentals of Programming I Search Algorithms

Searching One of the most important concepts in computer science We have all this information, so how do we find and extract what we want from it? A big business: for example, Google, a multi- billion dollar company, was originally based on a search engine (see The Search: How Google Rewrote the Rules of Business and Transformed Our Culture, by John Battelle)

Simple Searching in Python Determine whether or not a given element is in a collection of elements The in operator works with sequences and dictionaries Returns True if yes or False if no

>>> 'e' in 'power elite' True >>> 'k' in 'quagmire' False >>> 33 in [99, 22, 44, 33] True >>> 'name' in {'age':39, 'name':'jack'} True >>> 'Ken/1001' in self._accounts # a dictionary True Examples in uses == to compare for equality

How Does in Work? Loop through the collection and compare each element to the target element If the target equals the current element, return True After the loop is finished, return False

def reinventIn(target, collection): for element in collection: if element == target: return True return False Reinventing in Uses == to compare for equality The first return point quits as soon as a match is found The second return point quits if no match is found But: we can just use in with the collection instead! >>> reinventIn(33, [44, 22, 33, 111]) True

class Bank(object): def __init__(self): self._accounts = {} def __contains__(self, key): return key in self._accounts A Method for in Python runs __contains__ when it sees in >>> b = Bank() >>> b.add(SavingsAccount('Ken', '1001', )) >>> b.makeKey('Ken', '1001’) in b True

Other Types of Searches Determine whether or not a customer named ‘Ken’ has an account in the bank Find all of the accounts that –Have the name ‘Ken’ –Have a balance greater than $100,000 –Satisfy both of the above conditions –Satisfy any of the above conditions

def isNameInAnAccount(name, collection): for element in collection: if element.getName() == name: return element return None Satisfying a Property Works like in, but determines the presence or absence of an element with a given property in the collection Usually iterates over a sequence of objects Returns the object found or None isNameInAnAccount('Ken', self.accounts.values())) # Returns

def isBalanceInAnAccount(balance, collection): for element in collection: if element.getBalance() == balance: return element return None Match Other Properties Varies the method called to access the property in the element Otherwise, the code has exactly the same pattern isBalanceInAnAccount(10000, self.accounts.values())) # Returns None

def isBalanceInAnAccount(balance, collection): for element in collection: if element.getBalance() >= balance: return element return None Match Other Properties Might also vary the comparison used to detect the property isBalanceInAnAccount(10000, self.accounts.values()) # Returns = 10000>

def detect(test, collection): for element in collection: if test(element): return element return None def has10000(account): return account.getBalance() == Generalize as a detect Operation The search function should not know the details of the test function The test function is composed before detect is called The test function is passed as an argument to detect detect(has10000, self.accounts.values()) # Returns

def detect(test, collection): for element in collection: if test(element): return element return None def hasKen(account): return account.getName() == 'Ken' Generalize as a detect Operation Change the test function to redirect the search detect(hasKen, self.accounts.values()) # Returns

def detect(test, collection): for element in collection: if test(element): return element return None Simplify with lambda lambda creates an anonymous function on the fly, to be used just where it’s needed The lambda expression expects one argument and must return a Boolean value detect(lambda account: account.getName() == 'Ken', self.accounts.values()) # Returns

Find All the Elements that Satisfy a Given Criterion Simple detection finds and returns the first element that satisfies the search criterion Alternatively, we could find all the matching elements and build a list of them as we go Return this list This is just Python’s filter function!

Efficiency of Search Searches thus far have been sequential: each element in a collection must be visited, from beginning to end, before the target is found or we run off the end On the average, a simple sequential search stops halfway through the collection, but in the worst case, it must visit every element

Improving Efficiency: Binary Search If we assume that the elements are sorted, we can visit the relevant ones much more quickly Start at the collection’s midpoint (must be a sequence) If the target is less than the midpoint element, continue the search only to the left of the midpoint If the target is greater than the midpoint element, continue the search only to the right of the midpoint Will eventually hit the target or run out of elements

def binaryIn(target, collection): left = 0 right = len(collection) - 1 while left <= right: midpoint = (left + right) // 2 if target == collection[midpoint]: return True elif target < collection[midpoint]: right = midpoint - 1 else: left = midpoint + 1 return False Binary Search Assumes that the element in a collection supports the == and < operators