Computer Science 210: Data Structures. Searching

Similar documents
Analysis of Binary Search algorithm and Selection Sort algorithm

What Is Recursion? Recursion. Binary search example postponed to end of lecture

Binary search algorithm

Algorithm Analysis [2]: if-else statements, recursive algorithms. COSC 2011, Winter 2004, Section N Instructor: N. Vlajic

Lecture Notes on Linear Search

Loop Invariants and Binary Search

6. Standard Algorithms

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

Analysis of a Search Algorithm

Sorting Algorithms. Nelson Padua-Perez Bill Pugh. Department of Computer Science University of Maryland, College Park

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

Zabin Visram Room CS115 CS126 Searching. Binary Search

CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis. Linda Shapiro Winter 2015

Outline. Introduction Linear Search. Transpose sequential search Interpolation search Binary search Fibonacci search Other search techniques

Binary Heap Algorithms

Lecture Notes on Binary Search Trees

Sorting revisited. Build the binary search tree: O(n^2) Traverse the binary tree: O(n) Total: O(n^2) + O(n) = O(n^2)

Algorithms. Margaret M. Fleck. 18 October 2010

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

Binary Number System. 16. Binary Numbers. Base 10 digits: Base 2 digits: 0 1

Symbol Tables. Introduction

Sequential Data Structures

recursion here it is in C++ power function cis15 advanced programming techniques, using c++ fall 2007 lecture # VI.1

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

COMP 250 Fall 2012 lecture 2 binary representations Sept. 11, 2012

APP INVENTOR. Test Review

recursion, O(n), linked lists 6/14

Chapter 8: Bags and Sets

CS473 - Algorithms I

Data Structures. Algorithm Performance and Big O Analysis

4.2 Sorting and Searching

Chapter 7: Sequential Data Structures

CSC148 Lecture 8. Algorithm Analysis Binary Search Sorting

In mathematics, it is often important to get a handle on the error term of an approximation. For instance, people will write

Data Structures and Algorithms Written Examination

CSE 326, Data Structures. Sample Final Exam. Problem Max Points Score 1 14 (2x7) 2 18 (3x6) Total 92.

Functions Recursion. C++ functions. Declare/prototype. Define. Call. int myfunction (int ); int myfunction (int x){ int y = x*x; return y; }

Lecture Notes on Binary Search Trees

Recursion. Slides. Programming in C++ Computer Science Dept Va Tech Aug., Barnette ND, McQuain WD

Class : MAC 286. Data Structure. Research Paper on Sorting Algorithms

Efficiency of algorithms. Algorithms. Efficiency of algorithms. Binary search and linear search. Best, worst and average case.

csci 210: Data Structures Recursion

Near Optimal Solutions

2010/9/19. Binary number system. Binary numbers. Outline. Binary to decimal

Learning Outcomes. COMP202 Complexity of Algorithms. Binary Search Trees and Other Search Trees

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

This Unit: Floating Point Arithmetic. CIS 371 Computer Organization and Design. Readings. Floating Point (FP) Numbers

CSE373: Data Structures & Algorithms Lecture 14: Hash Collisions. Linda Shapiro Spring 2016

CSC 180 H1F Algorithm Runtime Analysis Lecture Notes Fall 2015

1 Description of The Simpletron

Closest Pair of Points. Kleinberg and Tardos Section 5.4

Binary Search Trees CMPSC 122

Data Structures and Algorithms

Linked Lists: Implementation Sequences in the C++ STL

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Motivation Suppose we have a database of people We want to gure out who is related to whom Initially, we only have a list of people, and information a

Sample Questions Csci 1112 A. Bellaachia

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

Section IV.1: Recursive Algorithms and Recursion Trees

Basic Programming and PC Skills: Basic Programming and PC Skills:

Automata and Formal Languages

A Note on Maximum Independent Sets in Rectangle Intersection Graphs

Heaps & Priority Queues in the C++ STL 2-3 Trees

Binary Division. Decimal Division. Hardware for Binary Division. Simple 16-bit Divider Circuit

Introduction to Parallel Programming and MapReduce

Chapter 13: Query Processing. Basic Steps in Query Processing

Positional Numbering System

Sources: On the Web: Slides will be available on:

Binary Multiplication

>

HW4: Merge Sort. 1 Assignment Goal. 2 Description of the Merging Problem. Course: ENEE759K/CMSC751 Title:

Node-Based Structures Linked Lists: Implementation

Chapter Objectives. Chapter 9. Sequential Search. Search Algorithms. Search Algorithms. Binary Search

A Randomized Searching Algorithm and its Performance analysis with Binary Search and Linear Search Algorithms

Converting a Number from Decimal to Binary

Analysis of Algorithms I: Optimal Binary Search Trees

Now is the time. For all good men PERMUTATION GENERATION. Princeton University. Robert Sedgewick METHODS

THE NUMBER OF REPRESENTATIONS OF n OF THE FORM n = x 2 2 y, x > 0, y 0

Sequences in the C++ STL

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Introduction to Programming (in C++) Sorting. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

The Union-Find Problem Kruskal s algorithm for finding an MST presented us with a problem in data-structure design. As we looked at each edge,

Constructing Contracts: Making Discrete Mathematics Relevant to Beginning Programmers

Recursion. Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive.

Time Limit: X Flags: -std=gnu99 -w -O2 -fomitframe-pointer. Time Limit: X. Flags: -std=c++0x -w -O2 -fomit-frame-pointer - lm

Regression Verification: Status Report

Regular Expressions and Automata using Haskell

What Is Recursion? 5/12/10 1. CMPSC 24: Lecture 13 Recursion. Lecture Plan. Divyakant Agrawal Department of Computer Science UC Santa Barbara

Elementary factoring algorithms

LINEAR INEQUALITIES. less than, < 2x + 5 x 3 less than or equal to, greater than, > 3x 2 x 6 greater than or equal to,

Discrete Optimization

Algorithm Design and Recursion

AP Computer Science AB Syllabus 1

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Transcription:

Computer Science 210: Data Structures Searching

Searching Given a sequence of elements, and a target element, find whether the target occurs in the sequence Variations: find first occurence; find all occurences find the number of occurences, etc Searching is a fundamental problem For simplicity, weʼll assume we have an array of n numbers double a[]; double target; and we want to write a method //return the position of first occurrence or -1 if not found int search (double a[], double target)

Searching //return the position of first occurrence or -1 if not found int search (double a[], double target)

Searching //return the position of first occurrence or -1 if not found int search (double a[], double target) { for (int i=0; i< a.length; i++) if (a[i] == target) return i; //if we got here, no element matched return -1; linear search

Searching //return the position of first occurrence or -1 if not found int search (double a[], double target) { for (int i=0; i< a.length; i++) if (a[i] == target) return i; //if we got here, no element matched return -1; best-case (fastest)? linear search worst-case (slowest)?

Searching //return the position of first occurrence or -1 if not found int search (double a[], double target) { for (int i=0; i< a.length; i++) if (a[i] == target) return i; //if we got here, no element matched return -1; With linear search, in the worst case we have to examine the entire input Can we do better? (that is, faster)? Yes, if the input is sorted linear search

Binary search Input: A target and a sequence of elements, sorted (in some order). For simplicity, we assume increasing (non-decreasing) order. //return the position of occurrence or -1 if not found //invariant: a is sorted in increasing order int binarysearch (double a[], double target) Idea: searching in a phone book open in the middle; if name comes before the middle name, search in the left half. if name comes after the middle name, search in the right half. Examples: double a[] = {1, 3, 4, 6, 7, 7, 9, 12, 14, 18, 56, 67, 89, 100; search for 6 search for 80

Binary Search //return the position of occurrence or -1 if not found //invariant: a is sorted in increasing order int binarysearch (double a[], double target) { int start, end, middle; start = 0; end = a.length-1; while...?... { middle = (start + end)/2; if (target == a[middle]) return middle; if (target < a[middle]) end = middle-1; if (target > a[middle]) start = middle +1; //if we are here, not found return -1;

Binary Search Correctness Is it ok to throw away half of the input? Why? Can you argue? Analysis: at the first iteration through the loop, start and end delimit the entire array at the second iteration through the loop, start and end delimit one half of the array at the third iteration... one quarter of the array at the fourth iteration... one eighth of the array let n be the size of the input array i th iteration ==> a section of size n/2 i How many iterations can there be?

Logarithm review

Assume n = 1,000, 000 Binary search How many elements does linear search compare? How many elements does binary search compare? Intuitively, binary search is (much) more efficient than linear search that is, in the worst case. We always think of the worst-case. Best-cases are irrelevant and offer no guarantees on the performance of an algorithm. We will analyze and compare them formally next week.

Binary Search Itʼs easy to think of it recursively Searching in the first or second half are recursive problems We need to give the start and end to the recursive call //invariant: a[] is sorted in increasing order //return the position where target is found, or -1 if not found int binarysearch (double a[], double target) { //this is the call to the recursive solver return binsearchrecursive(a, target, 0, a.length -1); // invariant: a[] is sorted in increasing order //search for target in a[start...end]; return the position where target is found, or -1 if not found int binsearchrecursive(double a[], double target, int start, int end)

Binary Search Itʼs easy to think of it recursively Searching in the first or second half are recursive problems We need to give the start and end to the recursive call // invariant: a[] is sorted in increasing order //search for target in a[start...end]; return the position where target is found, or -1 if not found int binsearchrecursive(double a[], double target, int start, int end) { //base case if (start < end) return -1; without base-case, infinite recursion //otherwise int middle = (start+end)/2; //note that it gets truncated if (target == a[middle]) return middle; if (target < a[middle]) return binsearchrecursive(a, target, start, middle -1); return binsearchrecursive(a, target, middle+1, end);