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