Sequential search. Building Java Programs Chapter 13. Sequential search. Sequential search

Similar documents
Building Java Programs Chapter 13

Searching & Sorting. Definitions of Search and Sort. Linear Search in C++ Linear Search. Week 11. index to the item, or -1 if not found.

CSCI 104 Sorting Algorithms. Mark Redekopp David Kempe

Today s Outline. Sorting: The Big Picture. Why Sort? Selection Sort: Idea. Insertion Sort: Idea. Sorting Chapter 7 in Weiss.

CSE 326: Data Structures Quicksort Comparison Sorting Bound

CSE 326: Data Structures Quicksort Comparison Sorting Bound

Insertion Sort. Divide and Conquer Sorting. Divide and Conquer. Mergesort. Mergesort Example. Auxiliary Array

Sorting and Algorithm Analysis

Sorting Review. Sorting. Comparison Sorting. CSE 680 Prof. Roger Crawfis. Assumptions

Searching and Sorting

Programming in Fortran 90 : 2017/2018

Sorting. Sorted Original. index. index

Sorting. Sorting. Why Sort? Consistent Ordering

CS1100 Introduction to Programming

Problem Set 3 Solutions

Sorting: The Big Picture. The steps of QuickSort. QuickSort Example. QuickSort Example. QuickSort Example. Recursive Quicksort

Course Introduction. Algorithm 8/31/2017. COSC 320 Advanced Data Structures and Algorithms. COSC 320 Advanced Data Structures and Algorithms

CSE 143 Lecture 16 (B)

CSE 143 Lecture 22. Sorting. reading: 13.1, slides adapted from Marty Stepp and Hélène Martin

More on Sorting: Quick Sort and Heap Sort

Esc101 Lecture 1 st April, 2008 Generating Permutation

CS221: Algorithms and Data Structures. Priority Queues and Heaps. Alan J. Hu (Borrowing slides from Steve Wolfman)

Design and Analysis of Algorithms

Kent State University CS 4/ Design and Analysis of Algorithms. Dept. of Math & Computer Science LECT-16. Dynamic Programming

CS240: Programming in C. Lecture 12: Polymorphic Sorting

An Optimal Algorithm for Prufer Codes *

Quicksort. Part 1: Understanding Quicksort

CMPS 10 Introduction to Computer Science Lecture Notes

Brave New World Pseudocode Reference

Priority queues and heaps Professors Clark F. Olson and Carol Zander

Complex Numbers. Now we also saw that if a and b were both positive then ab = a b. For a second let s forget that restriction and do the following.

News. Recap: While Loop Example. Reading. Recap: Do Loop Example. Recap: For Loop Example

Dijkstra s Single Source Algorithm. All-Pairs Shortest Paths. Dynamic Programming Solution. Performance. Decision Sequence.

CE 221 Data Structures and Algorithms

Introduction to Programming. Lecture 13: Container data structures. Container data structures. Topics for this lecture. A basic issue with containers

Dijkstra s Single Source Algorithm. All-Pairs Shortest Paths. Dynamic Programming Solution. Performance

Performance Evaluation of Information Retrieval Systems

The Greedy Method. Outline and Reading. Change Money Problem. Greedy Algorithms. Applications of the Greedy Strategy. The Greedy Method Technique

Assignment # 2. Farrukh Jabeen Algorithms 510 Assignment #2 Due Date: June 15, 2009.

Compiler Design. Spring Register Allocation. Sample Exercises and Solutions. Prof. Pedro C. Diniz

Module Management Tool in Software Development Organizations

such that is accepted of states in , where Finite Automata Lecture 2-1: Regular Languages be an FA. A string is the transition function,

Terminal Window. 11. Section 7 Exercises Program Memory Exercise 7-1 Swap Values in an Array Working memory Global Memory. 2 nd call 3 rd call

Machine Learning: Algorithms and Applications

6.854 Advanced Algorithms Petar Maymounkov Problem Set 11 (November 23, 2005) With: Benjamin Rossman, Oren Weimann, and Pouya Kheradpour

Lecture 5: Multilayer Perceptrons

Intro. Iterators. 1. Access

Parallel Numerics. 1 Preconditioning & Iterative Solvers (From 2016)

Dynamic Programming. Example - multi-stage graph. sink. source. Data Structures &Algorithms II

CSE 143 Lecture 14. Sorting

Non-Split Restrained Dominating Set of an Interval Graph Using an Algorithm

CHARUTAR VIDYA MANDAL S SEMCOM Vallabh Vidyanagar

Exercises (Part 4) Introduction to R UCLA/CCPR. John Fox, February 2005

Conditional Speculative Decimal Addition*

Lecture 3: Computer Arithmetic: Multiplication and Division

Support Vector Machines

Array transposition in CUDA shared memory

R s s f. m y s. SPH3UW Unit 7.3 Spherical Concave Mirrors Page 1 of 12. Notes

Steps for Computing the Dissimilarity, Entropy, Herfindahl-Hirschman and. Accessibility (Gravity with Competition) Indices

Hierarchical clustering for gene expression data analysis

Reading. 14. Subdivision curves. Recommended:

ELEC 377 Operating Systems. Week 6 Class 3

Computer models of motion: Iterative calculations

ON SOME ENTERTAINING APPLICATIONS OF THE CONCEPT OF SET IN COMPUTER SCIENCE COURSE

High level vs Low Level. What is a Computer Program? What does gcc do for you? Program = Instructions + Data. Basic Computer Organization

Parallel Solutions of Indexed Recurrence Equations

Solving two-person zero-sum game by Matlab

On Some Entertaining Applications of the Concept of Set in Computer Science Course

Machine Learning. Support Vector Machines. (contains material adapted from talks by Constantin F. Aliferis & Ioannis Tsamardinos, and Martin Law)

Life Tables (Times) Summary. Sample StatFolio: lifetable times.sgp

Private Information Retrieval (PIR)

Load Balancing for Hex-Cell Interconnection Network

Optimizing Document Scoring for Query Retrieval

An Application of the Dulmage-Mendelsohn Decomposition to Sparse Null Space Bases of Full Row Rank Matrices

Greedy Technique - Definition

9. BASIC programming: Control and Repetition

Solutions to Programming Assignment Five Interpolation and Numerical Differentiation

For instance, ; the five basic number-sets are increasingly more n A B & B A A = B (1)

Outline. Self-Organizing Maps (SOM) US Hebbian Learning, Cntd. The learning rule is Hebbian like:

S1 Note. Basis functions.

Computer Animation and Visualisation. Lecture 4. Rigging / Skinning


2x x l. Module 3: Element Properties Lecture 4: Lagrange and Serendipity Elements

Harvard University CS 101 Fall 2005, Shimon Schocken. Assembler. Elements of Computing Systems 1 Assembler (Ch. 6)

AMath 483/583 Lecture 21 May 13, Notes: Notes: Jacobi iteration. Notes: Jacobi with OpenMP coarse grain

Motivation. EE 457 Unit 4. Throughput vs. Latency. Performance Depends on View Point?! Computer System Performance. An individual user wants to:

Clustering Algorithm of Similarity Segmentation based on Point Sorting

Concurrent Apriori Data Mining Algorithms

Can We Beat the Prefix Filtering? An Adaptive Framework for Similarity Join and Search

LOOP ANALYSIS. The second systematic technique to determine all currents and voltages in a circuit

A Comparison of Top-k Temporal Keyword Querying over Versioned Text Collections

Lecture #15 Lecture Notes

Range images. Range image registration. Examples of sampling patterns. Range images and range surfaces

CS 534: Computer Vision Model Fitting

CHAPTER 2 PROPOSED IMPROVED PARTICLE SWARM OPTIMIZATION

Mathematics 256 a course in differential equations for engineering students

User Authentication Based On Behavioral Mouse Dynamics Biometrics

Cost-efficient deployment of distributed software services

CHAPTER 10: ALGORITHM DESIGN TECHNIQUES

FEATURE EXTRACTION. Dr. K.Vijayarekha. Associate Dean School of Electrical and Electronics Engineering SASTRA University, Thanjavur

Transcription:

Sequental search Buldng Java Programs Chapter 13 Searchng and Sortng sequental search: Locates a target value n an array/lst by examnng each element from start to fnsh. How many elements wll t need to examne? Example: Searchng the array below for the value 42: Copyrght (c) Pearson 2013. All rghts reserved. Notce that the array s sorted. Could we take advantage of ths? 2 Sequental search Sequental search search(a[], thngtofnd) start at the begnnng for each tem n A: f the tem s what we're lookng for: return ts locaton f we got ths far wthout returnng already, what we're lookng for sn't found return falure publc statc nt search(nt A[], nt thngtofnd) { for (nt =0; <A.length; ++) { f (A[]==thngToFnd) { return ; /* we ddn t fnd t. return falure */ return -1; 3 4

When Array Is Sorted When Array Is Sorted Ths array s already sorted Do we really need to go through entre thng before quttng? Suppose we re searchng for 38: we know once we ve reached A[10] that we ddn t fnd t /* verson 2. ONLY WORKS f A[] IS SORTED */ search(a[], thngtofnd) start at the begnnng for each tem n A <= thngtofnd: f the tem s what we're lookng for: return ts locaton 5 f we got ths far wthout returnng already, what we're lookng for sn't found. return falure 6 When Array Is Sorted Searchng a Sorted Lst What f we re orderng a pzza (and t s 1998)? Lookng for phone number of Sammy s Pzza Start wth the A s, then the B s, etc.? /* verson 2. ONLY WORKS f A[] IS SORTED */ publc statc nt search(nt A[], nt thngtofnd) { for (nt =0; <A.length && A[]<=thngToFnd; ++) { f (A[]==thngToFnd) { return ; return -1; 7 8

Bnary search (13.1) bnary search: Locates a target value n a sorted array/lst by successvely elmnatng half of the array from consderaton. How many elements wll t need to examne? Example: Searchng the array below for the value 42: mn md max The Arrays class Class Arrays n java.utl has many useful array methods: Method name bnarysearch(array, value) bnarysearch(array, mnindex, maxindex, value) copyof(array, length) equals(array1, array2) fll(array, value) sort(array) tostrng(array) Descrpton returns the ndex of the gven value n a sorted array (or < 0 f not found) returns ndex of gven value n a sorted array between ndexes mn /max - 1 (< 0 f not found) returns a new reszed copy of an array returns true f the two arrays contan same elements n the same order sets every element to the gven value arranges the elements nto sorted order returns a strng representng the array, such as "[10, 30, -25, 17]" 9 Syntax: Arrays.methodName(parameters) 10 Arrays.bnarySearch Usng bnarysearch // searches an entre sorted array for a gven value // returns ts ndex f found; a negatve number f not found // Precondton: array s sorted Arrays.bnarySearch(array, value) // searches gven porton of a sorted array for a gven value // examnes mnindex (nclusve) through maxindex (exclusve) // returns ts ndex f found; a negatve number f not found // Precondton: array s sorted Arrays.bnarySearch(array, mnindex, maxindex, value) // ndex 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 nt[] a = {-4, 2, 7, 9, 15, 19, 25, 28, 30, 36, 42, 50, 56, 68, 85, 92; nt ndex = Arrays.bnarySearch(a, 0, 16, 42); // ndex1 s 10 nt ndex2 = Arrays.bnarySearch(a, 0, 16, 21); // ndex2 s -7 bnarysearch returns the ndex where the value s found f the value s not found, bnarysearch returns: -(nsertonpont + 1) The bnarysearch method n the Arrays class searches an array very effcently f the array s sorted. You can search the entre array, or just a range of ndexes (useful for "unflled" arrays such as the one n ArrayIntLst) where nsertonpont s the ndex where the element would have been, f t had been n the array n sorted order. To nsert the value nto the array, negate nsertonpont + 1 nt ndextoinsert21 = -(ndex2 + 1); // 6 If the array s not sorted, you may need to sort t frst 11 12

Bnary search code // Returns the ndex of an occurrence of target n a, // or a negatve number f the target s not found. // Precondton: elements of a are n sorted order publc statc nt bnarysearch(nt[] a, nt target) { nt mn = 0; nt max = a.length - 1; whle (mn <= max) { nt md = (mn + max) / 2; f (a[md] < target) { mn = md + 1; else f (a[md] > target) { max = md - 1; else { return md; // target found Recursve bnary search (13.3) Wrte a recursve bnarysearch method. If the target value s not found, return ts negatve nserton pont. nt ndex = bnarysearch(data, 42); // 10 nt ndex2 = bnarysearch(data, 66); // -14 return -(mn + 1); // target not found 13 14 Exercse soluton // Returns the ndex of an occurrence of the gven value n // the gven array, or a negatve number f not found. // Precondton: elements of a are n sorted order publc statc nt bnarysearch(nt[] a, nt target) { return bnarysearch(a, target, 0, a.length - 1); // Recursve helper to mplement search behavor. prvate statc nt bnarysearch(nt[] a, nt target, nt mn, nt max) { f (mn > max) { return -1; // target not found else { nt md = (mn + max) / 2; f (a[md] < target) { // too small; go rght return bnarysearch(a, target, md + 1, max); else f (a[md] > target) { // too large; go left return bnarysearch(a, target, mn, md - 1); else { return md; // target found; a[md] == target 15 Bnary search and objects Can we bnarysearch an array of Strngs? Operators lke < and > do not work wth Strng objects. But we do thnk of strngs as havng an alphabetcal orderng. natural orderng: Rules governng the relatve placement of all values of a gven type. comparson functon: Code that, when gven two values A and B of a gven type, decdes ther relatve orderng: A < B, A == B, A > B 16

The compareto method (10.2) Runtme Effcency (13.2) The standard way for a Java class to defne a comparson functon for ts objects s to defne a compareto method. Example: n the Strng class, there s a method: publc nt compareto(strng other) A call of A.compareTo(B) wll return: a value < 0 f A comes "before" B n the orderng, a value > 0 f A comes "after" B n the orderng, or 0 f A and B are consdered "equal" n the orderng. effcency: A measure of the use of computng resources by code. can be relatve to speed (tme), memory (space), etc. most commonly refers to run tme Assume the followng: Any sngle Java statement takes the same amount of tme to run. A method call's runtme s measured by the total of the statements nsde the method's body. A loop's runtme, f the loop repeats N tmes, s N tmes the runtme of the statements n ts body. 17 18 Effcency examples Effcency examples 2 statement1; statement2; statement3; 3 for (nt = 1; <= N; ++) { statement4; for (nt = 1; <= N; ++) { statement5; statement6; statement7; N 3N 4N + 3 for (nt = 1; <= N; ++) { for (nt j = 1; j <= N; j++) { statement1; for (nt = 1; <= N; ++) { statement2; statement3; statement4; statement5; N 2 4N N 2 + 4N 19 How many statements wll execute f N = 10? If N = 1000? 20

Algorthm growth rates (13.2) We measure runtme n proporton to the nput data sze, N. growth rate: Change n runtme as N changes. Say an algorthm runs 0.4N 3 + 25N 2 + 8N + 17 statements. Consder the runtme when N s extremely large. We gnore constants lke 25 because they are tny next to N. The hghest-order term (N 3 ) domnates the overall runtme. We say that ths algorthm runs "on the order of" N 3. or O(N 3 ) for short ("Bg-Oh of N cubed") Complexty classes complexty class: A category of algorthm effcency based on the algorthm's relatonshp to the nput sze N. Class Bg-Oh If you double N,... Example constant O(1) unchanged 10ms logarthmc O(log 2 N) ncreases slghtly 175ms lnear O(N) doubles 3.2 sec log-lnear O(N log 2 N) slghtly more than doubles 6 sec quadratc O(N 2 ) quadruples 1 mn 42 sec cubc O(N 3 ) multples by 8 55 mn............ exponental O(2 N ) multples drastcally 5 * 10 61 years 21 22 Bnary search (13.1, 13.3) bnary search successvely elmnates half of the elements. Algorthm: Examne the mddle element of the array. If t s too bg, elmnate the rght half of the array and repeat. If t s too small, elmnate the left half of the array and repeat. Else t s the value we're searchng for, so stop. Whch ndexes does the algorthm examne to fnd value 22? What s the runtme complexty class of bnary search? ndex 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 value -4-1 0 2 3 5 6 8 11 14 22 29 31 37 56 23 Bnary search runtme For an array of sze N, t elmnates ½ untl 1 element remans. N, N/2, N/4, N/8,..., 4, 2, 1 How many dvsons does t take? Thnk of t from the other drecton: How many tmes do I have to multply by 2 to reach N? 1, 2, 4, 8,..., N/4, N/2, N Call ths number of multplcatons "x". 2 x = N x = log 2 N Bnary search s n the logarthmc complexty class. 24

Sortng sortng: Rearrangng the values n an array or collecton nto a specfc order (usually nto ther "natural orderng"). one of the fundamental problems n computer scence can be solved n many ways: there are many sortng algorthms some are faster/slower than others some use more/less memory than others some work better wth specfc knds of data some can utlze multple computers / processors,... Sortng methods n Java The Arrays class n java.utl has a statc method sort that sorts the elements of an array Strng[] words = {"foo", "bar", "baz", "ball"; Arrays.sort(words); System.out.prntln(Arrays.toStrng(words)); // [ball, bar, baz, foo] comparson-based sortng : determnng order by comparng pars of elements: <, >, compareto, 25 26 Selecton sort selecton sort: Orders a lst of values by repeatedly puttng the smallest or largest unplaced value nto ts fnal poston. The algorthm: Look through the lst to fnd the smallest value. Swap t so that t s at ndex 0. Look through the lst to fnd the second-smallest value. Swap t so that t s at ndex 1.... Repeat untl all values are n ther proper places. Intal array: Selecton sort example value 22 18 12-4 27 30 36 50 7 68 91 56 2 85 42 98 25 After 1st, 2nd, and 3rd passes: value -4 18 12 22 27 30 36 50 7 68 91 56 2 85 42 98 25 value -4 2 12 22 27 30 36 50 7 68 91 56 18 85 42 98 25 value -4 2 7 22 27 30 36 50 12 68 91 56 18 85 42 98 25 27 28

Selecton sort code // Rearranges the elements of a nto sorted order usng // the selecton sort algorthm. publc statc vod selectonsort(nt[] a) { for (nt = 0; < a.length - 1; ++) { // fnd ndex of smallest remanng value nt mn = ; for (nt j = + 1; j < a.length; j++) { f (a[j] < a[mn]) { mn = j; Selecton sort runtme (Fg. 13.6) What s the complexty class (Bg-Oh) of selecton sort? // swap smallest value ts proper place, a[] swap(a,, mn); 29 30 Merge sort Merge sort example sort: Repeatedly dvdes the data n half, sorts each half, and combnes the sorted halves nto a sorted whole. ndex 0 1 2 3 4 5 6 7 value 22 18 12-4 58 7 31 42 The algorthm: Dvde the lst nto two roughly equal halves. Sort the left half. Sort the rght half. Merge the two sorted halves nto one sorted lst. 22 18 12-4 22 18 12-4 22 18 12-4 18 22-4 12 58 7 31 42 58 7 31 42 58 7 31 42 7 58 31 42 Often mplemented recursvely. -4 12 18 22 7 31 42 58 An example of a "dvde and conquer" algorthm. Invented by John von Neumann n 1945 31-4 7 12 18 22 31 42 58 32

Mergng sorted halves Merge halves code // Merges the left/rght elements nto a sorted result. // Precondton: left/rght are sorted publc statc vod (nt[] result, nt[] left, nt[] rght) { nt 1 = 0; // ndex nto left array nt 2 = 0; // ndex nto rght array 33 for (nt = 0; < result.length; ++) { f (2 >= rght.length (1 < left.length && left[1] <= rght[2])) { result[] = left[1]; 1++; else { result[] = rght[2]; 2++; // take from left // take from rght 34 Merge sort code // Rearranges the elements of a nto sorted order usng // the sort algorthm. publc statc vod Sort(nt[] a) { // array nto two halves nt[] left = Arrays.copyOfRange(a, 0, a.length/2); nt[] rght = Arrays.copyOfRange(a, a.length/2, a.length); // sort the two halves... // the sorted halves nto a sorted whole (a, left, rght); Merge sort code 2 // Rearranges the elements of a nto sorted order usng // the sort algorthm (recursve). publc statc vod Sort(nt[] a) { f (a.length >= 2) { // array nto two halves nt[] left = Arrays.copyOfRange(a, 0, a.length/2); nt[] rght = Arrays.copyOfRange(a, a.length/2, a.length); // sort the two halves Sort(left); Sort(rght); // the sorted halves nto a sorted whole (a, left, rght); 35 36

Merge sort runtme What s the complexty class (Bg-Oh) of sort? 37