Searching Algorithms



Similar documents
Zabin Visram Room CS115 CS126 Searching. Binary Search

Analysis of Binary Search algorithm and Selection Sort algorithm

Binary search algorithm

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

CSC 180 H1F Algorithm Runtime Analysis Lecture Notes Fall 2015

Pseudo code Tutorial and Exercises Teacher s Version

AP Computer Science A - Syllabus Overview of AP Computer Science A Computer Facilities

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

Computer Programming I

Data Structures. Algorithm Performance and Big O Analysis

Computing Concepts with Java Essentials

Algorithms and Data Structures Written Exam Proposed SOLUTION

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards

dictionary find definition word definition book index find relevant pages term list of page numbers

Binary Heap Algorithms

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

COMPUTER SCIENCE. Paper 1 (THEORY)

8.1. Example: Visualizing Data

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A

AP Computer Science Java Mr. Clausen Program 9A, 9B

CPLEX Tutorial Handout

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

Introduction to Programming System Design. CSCI 455x (4 Units)

The Java Collections Framework

Binary Heaps * * * * * * * / / \ / \ / \ / \ / \ * * * * * * * * * * * / / \ / \ / / \ / \ * * * * * * * * * *

Loop Invariants and Binary Search

cs2010: algorithms and data structures

DNS LOOKUP SYSTEM DATA STRUCTURES AND ALGORITHMS PROJECT REPORT

4.2 Sorting and Searching

An Incomplete C++ Primer. University of Wyoming MA 5310

CPSC 121: Models of Computation Assignment #4, due Wednesday, July 22nd, 2009 at 14:00

Conditionals (with solutions)

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)

Chapter 2: Elements of Java

Introduction to Parallel Programming and MapReduce

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,

LINKED DATA STRUCTURES

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

ALLIED PAPER : DISCRETE MATHEMATICS (for B.Sc. Computer Technology & B.Sc. Multimedia and Web Technology)

CS 111 Classes I 1. Software Organization View to this point:

6. Standard Algorithms

Evaluation of Complexity of Some Programming Languages on the Travelling Salesman Problem

CompSci-61B, Data Structures Final Exam

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:

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Data Types. Abstract Data Types. ADTs as Design Tool. Abstract Data Types. Integer ADT. Principle of Abstraction

Fast Arithmetic Coding (FastAC) Implementations

KS3 Computing Group 1 Programme of Study hours per week

CS170 Lab 11 Abstract Data Types & Objects

AP Computer Science AB Syllabus 1

Introduction to Object-Oriented Programming

Analysis of a Search Algorithm

Computer Programming I & II*

7.1 Our Current Model

CSC148 Lecture 8. Algorithm Analysis Binary Search Sorting

Randomized algorithms

Analysis of Algorithms I: Optimal Binary Search Trees

Part 3: GridWorld Classes and Interfaces

AP Computer Science Java Subset

NP-Completeness I. Lecture Overview Introduction: Reduction and Expressiveness

This lecture. Abstract data types Stacks Queues. ADTs, Stacks, Queues Goodrich, Tamassia

Binary Heaps. CSE 373 Data Structures

Symbol Tables. Introduction

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

Moving from CS 61A Scheme to CS 61B Java

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Computer Programming I

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

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

D06 PROGRAMMING with JAVA

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

Binary Trees and Huffman Encoding Binary Search Trees

CS/COE

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

IMPROVING PERFORMANCE OF RANDOMIZED SIGNATURE SORT USING HASHING AND BITWISE OPERATORS

Output: struct treenode{ int data; struct treenode *left, *right; } struct treenode *tree_ptr;

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

Introduction to Data Structures

Section IV.1: Recursive Algorithms and Recursion Trees

Image Compression through DCT and Huffman Coding Technique

Data Structures and Data Manipulation

1. What are Data Structures? Introduction to Data Structures. 2. What will we Study? CITS2200 Data Structures and Algorithms

RARITAN VALLEY COMMUNITY COLLEGE COURSE OUTLINE. CISY 103 Computer Concepts and Programming

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

Lecture 2: Data Structures Steven Skiena. skiena

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

Load Balancing and Rebalancing on Web Based Environment. Yu Zhang

STORM. Simulation TOol for Real-time Multiprocessor scheduling. Designer Guide V3.3.1 September 2009

Tables so far. set() get() delete() BST Average O(lg n) O(lg n) O(lg n) Worst O(n) O(n) O(n) RB Tree Average O(lg n) O(lg n) O(lg n)

COMPUTER SCIENCE A. Course Description

Number Systems and Radix Conversion

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

Curriculum Map. Discipline: Computer Science Course: C++

#820 Computer Programming 1A

Java Classes. GEEN163 Introduction to Computer Programming

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

Java Application Developer Certificate Program Competencies

Arithmetic Coding: Introduction

Transcription:

Searching Algorithms

The Search Problem Problem Statement: Given a set of data e.g., int [] arr = {10, 2, 7, 9, 7, 4}; and a particular value, e.g., int val = 7; Find the first index of the value in the data. e.g., return index = 2

The Search Problem Problem Statement, revisited: Input: A set of data (an array, ArrayList, LinkedList, ) A single data element Output: Position of the data element in the data set, or -1 if the element does not appear in the data set

Linear Search Algorithm # Input: Array D, integer key # Output: first index of key in D, # or -1 if not found For i = 0 to last index of D: if D[i] equals key: return i return -1

Linear Search for Phone Numbers # Input: Array D of Business objects, # phone number key # Output: first index where key s phone # number matches D, or -1 if not found Business: phone # address name For i:= 0 to end of D: if D[i].phone matches key: return i return -1

Exercise 1. Implement a class called Business that includes fields for name, address, and phone number, plus a constructor and accessor methods. 2. Create a class called YellowPages that stores a set of Business objects in an array. 3. Write a LinearSearch method for the YellowPages class that finds the index of a Business, given its phone number.

Binary Search

What happens if our array is huge? Imagine finding a particular word on the Web (approximately 100,000,000,000 documents) Linear search would take a long time Two common faster search techniques are: Indexing (used on the Web and in databases) Binary search We ll discuss binary search because it s simpler, but you can learn about indexing in later CIS classes

An Example Search Problem Imagine flipping through the Yellow Pages, looking for a pizza place near you. It s pretty easy you just flip to the section for P, then look for Pi, then Piz,, Pizza. Now imagine doing the reverse: find the name of a business given just their phone number. What algorithm will find the number in the phone book? Answer: you need to use (some version of) linear search! Ugh.

Binary Search: Normal Phone Book Use Normally, when you search the phone book, you implicitly use the fact that it s sorted: The smallest element (alphabetically first element) appears first. Then the next smallest, Then the biggest (alphabetically last) element. Binary search does the same thing, and it only works if your data (array) is sorted.

Binary Search Example Step 1: Define left and right boundaries for searching Step 2: Define middle of the search region Step 3: Compare the middle with our key Repeat! Find key: 29 Comparison: D[mid] < key Comparison: D[mid] = key! -15-7 -6-2 0 8 10 29 31 40 left mid left mid right

Binary Search Algorithm # Input: Sorted Array D, integer key # Output: first index of key in D, or -1 if not found left = 0, right = index of last element while left <= right: middle = index halfway between left, right if D[middle] matches key: return middle else if key comes before D[middle]: // b/c D is sorted right = middle -1 else: left = middle + 1 return -1

You guessed it: Exercise Implement a binary search method in your Business class

How much faster is binary search? Way, way faster Assuming the array is already sorted But precisely how much? For an array of size: Linear search might visit: Binary search might visit: 2 4 = 16 16 elements 4+1 = log 2 (16)+1 2 8 = 256 256 elements 8+1 = log 2 (256)+1 2 12 = 4096 4096 elements 12+1 = log 2 (4096)+1 2 n = m elements m elements n + 1 = log 2 (m) + 1

Arrays.binarySearch The Java class Arrays has numerous helpful methods built in, including a binary search method: public static int binarysearch(int[] a, int key): Searches the specified array of ints for the specified value using the binary search algorithm. Example: int index = Arrays.binarySearch(arr, 29);

Binary Search: What you should know 1. The requirements for it to work (array is sorted) 2. How to simulate it on an example array That is, what sequence of indexes are compared with the key for a specific input key? 3. Write the algorithm for it 4. Advantages and Disadvantages compared with linear search 5. How to use Arrays.binarySearch()

Exercise Modify your Business class so that the Arrays.sort() method will work on it What are the two things you need to do? Declare that the class implements the Comparable interface Implement the compareto() method Make it sort the Businesses according to phone number