New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here

Java Programming

by: Kathryn Eichmann

Java Programming COP 2250

Kathryn Eichmann
GPA 3.8


Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Class Notes
25 ?




Popular in Course

Popular in Computer Programming

This 121 page Class Notes was uploaded by Kathryn Eichmann on Monday October 12, 2015. The Class Notes belongs to COP 2250 at Florida International University taught by Staff in Fall. Since its upload, it has received 9 views. For similar materials see /class/221732/cop-2250-florida-international-university in Computer Programming at Florida International University.


Reviews for Java Programming


Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 10/12/15
Java 5 Illuminated jve Learning Approach Herv Franceschi e Chapter 9 quot Multidimensional Arrays and the ArrayList Class Topics 39 Declaring md W3 Multidimensional Mays Aggregae Twnimensional Array Operations 39 0mm Multidilmmional Arrays o The Armyle Class TwoDimensional Arrays Allow organization of data in rows and columns in a table like representation Example 7 Daily temperatures can be arranged as 52 weeks with 7 days each Declaring Multidimensional Arrays o Declaring atwo dimmsimal array datatype H1 array am 0f datolypt H1 sxray aml uray amez lea nga nwdhmnsiomlmuy datatypa 111 arraymm or datatypa 11 axray ansl tawny92 a 39 Examples double 1 dzuyTamp wakiy hmn Auto HM cars Instantiating MultjDimensional Arrays a Instan a ngatwwdimcnsionalmay array am m datum 2le epo where expl and exp are wresslons that wanna to 11th and smify rupacttvnly this mum at tows and the number of column in the array Example dailyl amps my Gamble 5211 da miihas 52 mm and helium fora total of 364 clcmems Default Initial Values c When an army is instantiated the array elements am given standard default values identiml m default value cf lmsdimensional arrays data mm 1m Assigning Initial Values dataty pa H1 arrly am x i 4 valuarw value l N valuIlO Vslunllg m M i when vegan is m expr ssion that walnut to than an type M the array and 1 the vulva to Hum 120 the element at roar M and toqu It The nmnher of nuhlim is the number of sum in the array The number nf values in each sublist Wines the numbc ofcolunma in that row v Thus a twodimemioml man have aidiffcmm numbcr a calumm in each row Assigning Initial Values Example For example this statement int numbersLlstl O 5 10 0r 3 6 9 1 instantiates this array m x i m I m m m 21 m m An Array of Arrays a As the ooding gum illustrates a two dimcnsional array is an array of arrays 7 The first dimennion of a wovdimensimal my is an array ofamy references with each rcfcm pointing to a tingleamnmnal array nusan unyisz of anarray ofmws whmeuhmwisuinglen dimmsional army Instantiating Arrays with Rows of Different Length a To instantiate a twndimensianal may with a diffcmm numba of mlumns for each row 1 inmmiaee In twoaimsional array 2 instantiate each m as a singbdimcmional WY Hinstantuw mm atzay with 3 rows char UH grads mu chat tilt 1 instantute much 20 graham nan char 13 H inanimate row 13 gtaci39esil new what is H inanimate rm 1 graaauz a mu Chat 12 ff instantiate n 2 Accessing Array Elements a Elements and a twodimnnsimal array are accessed using thin syntax arxammtmn mp2 exp in the emf vow position or am index V mm index of first raw 0 mwindcxoflaammumbaofmm l po isthe chum colmn Worm index cohlmnindex affmcdm I cnksmn indcx of last column nmnbcr 6f cohmmsimmmmwvl The Length of the Array The umber of rows in a twodimensional array is array mm length Thenumherofcdumminmwa inatwo dimcnsimal army is arraynumin 4 length Summary Accessing Two Dimensional Array Elements mum I await Example Family Cell Bills We want to analyze three months of cell phone bills for a family of four See Example 91 FamilyCellBillsjava Aggregate Array Operations To process all array elements in row order we use a nemd far Imp far m i z i c utaMJenqth 1H i for mt j U j c aray ml length 3w pmsz 91mm Examine le 3 v The mm 1039 W the rum v Tummmmmewlm mmme 39 See Etmple 93 0mpuFamilyCdlBilejam Processing a Given Row a If we want to nd the maximum bill for a particular month or the lots bills for a month we need to punts at me now a Topmcwjustmw E we maxi standard Emu fer m 3 m j c art7mm lemqth j pwmss ginmt art smmm 11 See Emmple 94 SnMeme lyCdlBitlim Processing a Given Column If We want to determine the highest cell bill for on perm we need to pmccssjust one column To procau just mhmj m use this standard form for e 1m 1 In 2 atty tn lcng ch 1H l 1 4 j lt arraymmlilJazamh H prawns almm Arruy mulljl Because rows have variable lengths 2mm verifythatlhe currenth uncallqu berm aan to pmccaa the airman See Examplz 95 MmeerBiILjaw Processing One Row at a Time 39 Ifwe wantmdcterminememmlufthece bills for each month we need to pmcess all rows calculating a total mum and ofcach NW Weuwthiutandmikxm far mat in Q i e mlykm lwth 1H imtialiu prounimg vasuhhs for 2m 1 for int j m j 2 atrammxlangth jw prom 91mm arraymmuuj N and inner at X905 Mush tha promssinq 02 row i i and mike for loop Sc Empie 96 S umEachRawF mdyCclleIwam Common Error Trap o Failing to initiallzxe the row processing variables before processing each m is a logic error and will general mm lemlts Processing A Column at a Time Supposewcwamwmtesxgradesformee warm Each mum has a diffarem number of 331580 mhmhas amt number of mlnmm mt m3 and 1 83 75 3 4 25 92 m L 186 86 95 3 H First we needw ndnunmnhcr of wlmmsin thclxgcstmwWeusethninmbapcmditim Thmhefmmmmp ngwpmthem elmem we check whammch aim in thccm39rmtmw Processing A Column at a Time can t 0 We havc stand the maximum number of columns in mameberO 39almx the general palm for processmg elcnmmmc column at a time is for um 3 9 j lt mumumeCMumns 3 for 3 1m 339 0 1 aray mllenqth 1 7 I class mum 3 mm in mm mm 1f 3 lt attaWamtilJemzth 3 l procass element axrayuamettl 3 9 7 Gmdc mcez w 39ava o o o DmmwmgAmeMa aBm Chart We use our standard nested for loops and the fillRect method of the Graphics class for the bars and the drawString method to print each element s value WI oau 5667 3255 25m 5529 ten 32m 2611 I I I I mm m 3455 um To change colors for each row we use an array of Color objects and loop through the array to set the color for each row APplElstaned Each time we process a row we must reset the X and y values for the first bar See Example 98 BarChartApplet java Other Multidimensional Arrays If w want to kecp ml of sales on a per year perweek and pmday basis We could use a three dimmsimal array 1quot dimensim year 7 2quot dimension week 3quot dimension day of the weak Sample Code declare a tmemrdlmenslonal array double HM sales inscamtuta that arzay for 10 years 52 weeks and 7 ays aalss new daublt 101521 set the valm at um first elumnt minim 0 3 63650 H Set the valm for y a week 22 day 3 sales HH2Z 3 928426 H 52 the last value m the tray sales 9H51 6 1234450 Structure of an nDimensional Array Array General Pattern for Processing a ThreeDimensional Array for int 1 39 0 i vi array mllength l for wt 3 0 j lt array mlilJength 3H for mt k U k uraf wliltjlrlenqth kw f procaxa thl elemarm axxly mtllljltk Code to Print sales Array for int 1 0 I lt salesllength 1 for t 11 j G j 4 salesiullength j for f m k U I lt 51153I1Hlengthi kw prxnf the clam at 531mm 3 k1 Systemwt pruztg aaleslxnjllkj quotktquot H Skip a line after each quotall ayatemwuumimlm 3 H skip a hive after each month ystemlouLpt1ntlm H A FourDimensional Array a If we want to keep ack of sales on a perslate per year pcpwcek and peroday basis We could use a four dknmnimal may I m state 7 2quot oiimcnsion ya 3 dimsensim week 43931 dimension dayofthcwwk doublanu m1 sales my damn rmumjtnlm General Pattern for Processing a FourDrmensronal Array for int i O L lt arraymame length 1 for int j U j lt umy amlilllgnqth j for 1111 k 0 k lt armymmlilljblengm k for mt 1 9 1 c armymmtilljlmvlenqth 14 process element rxaymmtillj MU The ArrayList Class Arrays haw a xed m were they have been instantiated What if we39dm t know how my elements wc will need Forename weave reading values frum a 111 returning snatch mulls We could createam Inseam butuwn we waste pme far all unused element A better idea i to use mama M m elements of object mm and automatically expands its size as needed The ArrayList Class a Package java aril Q All ArmyLm elements an object refcmnces so We could have an AmyIJn of Auto objects Book objects Shiny etc c To store primitiw types in an ArmyLm use the wrapper clam Integer Mable Human 8001mm an Declaring an ArrayList Use this syntax krraymsug Armryust am is Mammalsme Iheqpcofobjec mfmth w lbeamedmthem zy n For cman Arranystmrznqgt liltaistxingai ArrayListzAutw 111109333 Arraymatdmmw manna 39 The Armyuu is a semi dost The AW classhashecnwrinensom itcan Modem references ofany type speci ed by the client ArrayUst Constructors Cunslructor name and argument list Arraym M gt mmrmmbkmhim type wuh an initial W of l I Mraymxtstgu in initialcmcity maWe de mm WTmWW The mpadty of 81W is the total limbs ofelemmm allocated to the list v ThesiuofanmAmyumnhtnmdmmc clmnmhatamuwd Instantiating an ArrayLiSt This list has a capacity af 10 Astronaut references but 8 Kill of 0 Arrayustastzonwz luwtutronauts DW nrayListaaummutM 6 This list has a camoin 5 String ban has a size cf 0 Arrnyhistlt5tmnggt lumtsumq new ArrayLLstdt Wi 5 in ArrayList Methods 5 meend oflhe list mmnu ndmmxsinmelm mumman wt 2 More ArrayList Methods list Lat mmoknmammmmmdgx mi in I i z m Mofma ummm uize Processing Array Lists Using a simdxd for loop Class am currmmt bj ct for 4 1n 1 0 x 4 axunLG 1 currenzobjm th m VW A 3 pavan mzranmhject Example Ant 0 currenthuhe far t not 3 x U 1 lt lxstonuutosauot 7 iv 1 currentauto x listsfhutousuwti i M if process cutnmtlute The Enhanced for Loop a Simpli es processing of lists o The Ward formis for Claufum cuzrwnwbjact arrayLlstName I process mrronwbj oct This whamd rloup xintsallcletmnu of an ArmyLm af String named in for z stung s 2 Int 3 systgmwuupzmtlm 9 339 2 See Exch 912 Amy xtO megmjam Using an ArrayLiSt We want to write a mum fur a bookstore that allows users we search In books using keywords We will hawthmeclum mm program A Book all with instance mamas representing an title author and price Amwmmmam8wtobjmmm Amylixt and Wide a taarski amdc method A BunkSeathngiu 1388 Which provides the use imam and the mix method SwExamplex 913 914 amp 915 Topics Declaring md W3 Arrays Accessing Amy Elements Wriling Methods Aggmgnn Array Operations Using Arrays in Claus Swelling and Setting Amy Using Arrays as Imam Arrays a An array is a sequence of variables of the same data type The data type can be my of Java s primitive types int slum by lugs rms doable bodes char or 1 ch Bach va39iahleinlhemyismdcmenk Weuacanlnduwspacifythepoaitimofm element in the may Arrays are uaeful fat many applications including calculamg statistbsutmpmun glhemofa game Declaring and Instantiating Arrays a Arrays are 013 so creating an array requires two steps 1 dalering mrefermtokmy 2 mumbling the my Todeclm quotdam to many means syntax datatypa I array m To mantis an my use am mm artayk iame max dacacypal size I where size is an uxpmuion thin evaluates m an mugm and 3935123 tin mm of almnts Examples Declaring arrays double duly39remps laments are doubles String 1 Tracks I elmnts are Strings boolean L anstexts f alumna Me booleans Auto 1 mm H animate we Auto rezwences int 1 calm b10201 if cm 1mm Arrays Instantia ng these aways daily remps may Gambian jl if 385 laments CdTrAcka NEW stzingtn if 15 lm i humIOfQUQSLiOB i I 30 answrs 39 may bmlmtaumwfouvttionsll can new Autot c9101 new 1mm b10201 new mus if a almnm Default Values fur Elements When an array is instantiated the elements are assigned de ant value according to the army data WIquot type value alien 0 We a spa Ids trad Combining the Declaration and Instantiation of Arrays Syntax datuype I array am new datatypeslze Examplcs down I daijy39tsmpa new daublN S string 1 Cd t remks new Stringllsh mt numberotqmtwm 3 boolaan 1 answrs mu boemmtnummmuutmnsla huto 1 cars new autGIf int c3101 Dav IKEIS b10261 mi intHI Assigning Initial Values to Arrays Arrays can be instantiated by specifying a list of initial values v Syntax danith I unmet value vAluel what value 1 an Wrassmvn valuating to the data 1m 3 than any am is the value to assign ta the 211mm at ind 39 Examplm lht mac 5 9 in n oddnumbazs i 1 3 3 7 mm mm s 2 13 15 1 1 3 Ante sportscar a new Autel warrenquot 0 0 0 31 Ante H cats s sportsman mm must 9 nae AutoE BW39 1013 15413 l H Common Error Trap An initialization list can be given only when the array is declared 7 Attempting to assign values to an array using an initialization list after the array is instantiated will generate a compiler error The new keyword is not used when an array is instantiated using an initialization list Also no size is specified for the array the number of values in the initialization list determines the size of the array Accessing Array Elements a Tommelemnofmarraymsemissynm array amelexp whera x is an expression that evaluates to an i tag r expismcclqmnt slmniupmmmwithin the may Themdtxnf n mdamlinmmko lengthisamd Only Megainmva able that hx dsmenmnherdehmnindxmmdia mmdusingmissynm array amelength Common Error Trap Attempting to access an element of an array using an index less than 0 or greater than arrayName length 7 I will generate an ArrayIndexOutOfBaundsExceptian at run time Note that for an array length 7 Without parentheses 7 is an instance variable Whereas for Strings length 7 with parentheses 7 is a method Note also that the array39s instance variable is named length rather than size Accessing Array Elements array G 39 See Example 81 Cemwm 5swwraao 5sgaa ps za ao 15 za ao ns za ao sanlm glutl l sse 191w pmeuumsm IIqu aw 122921 Instanliating an Array of Objects To instantiate an army with a class data type 1 inm alc the my 2 mammal the objacm E instanuata array all 31me are null Auto 1 can neat Aumb instantiua objmts And assign to alumna Auto sportst 3 ma Auto mau um 30 w carslol u spouse carall new Auto n carsm 15 still null 39 Ste Example ZAumArmyjam Aggregate Array Operations a We can perform thc mm optratims on arrays as we do an a mice at iaput values 7 calculate the mm mm A nd the average vain w find 1 Wm mum vahn an Taperfmmmapemhnonaneminan mayweuscu rrlmpmpwfmnlhema m oneachelmminmm Standard for Loop Header for Array Operations for int 1 U i i rraywame length 1 7 initializaka awn in 1 0 jereates indcxiandwtsltm lc fimelemu 0 loop moditim x lt nrxagmm length conmuas execution until the and of thc any is reached loapnpdmc u m1thwa next element 0 mm pm each element inordcrv In dethe jbr loop wemfmwe the current elmm uray amx x Priming All Elements of an Array a Exampl z This code prints each element in an array named maxim out clement per line assuming that cell ill has baa instmtiated for 1m 1 a 0 i lt rung31131qu 1 y Systmnl an prlntlm 581131113 5 See Example 83 PrmWEWJam Reading Data Into an Array a Exampl z this code reads values from the user into an away nancd swank which has previously been mm Scanner ran m Scams Bystamdn i fer int 1 G J z callkillngngth 1H Systemmuhptxnzg Exxtez Ml gt H osllmllstn scammxthoum t See Example amp4 Rea ugDaMmoAMmyava Summing the Elements of an Array a Exampl z this coda calculates the tum value of all elements in an my nmmd ceile Ils which has p cvkun ytmeniMSUInhued double tatal 60 I initzalxze tatal for lt mt 1 m 2 i calllxll dcngtm l f total n 1181113111 Mswmlautmrlntlm w tats is quot 9 total H a See Exmaple 85 SumngAmyElWJava Finding MaximumMinimum Values a Exampl z this code nds the maximum value in an array named mama make rst 010m tbs Current maximum double mnxvuue mllBilixlO Start for loop elem 1 for 4 1m 1 1 i lt callmilzs lengtm l r J i if callmllatij mux ulue maxValm Callmll lil System out printlm fhe maximum 1 39 Maine I 39 See Exmnplc 86 MGMWayVafuejava Copying Arrays a Suppose we want to copy the elements of an array to another myy We wold try this code double 1 billsbtckup v new double 6 bills achm milling if iamznacti Ahlmugh this made mnpilcx it is logically incorrecch are copying the 3mm object term to the billsz ashram We at not copying the my m 39 Theth ufthiscodei stamina menus dc Copying Array References billsBackup cellBlllS has this effect hlls ackup ceuamsm hlls ackup1 4 cell lllsU hlls ackup2 4 cell msm hlls ackup3 4 ceuamsm buxsaackupm 4 ceuamsm 1 hlls ackup5 4 ceuamsm Copying Array Values a Example this code copies the values of all elements in an my names aiming to an array mmch billa ackap bah of which haw previously been inmtiamd with the mm length for lt ml 1 m 2 lt mlllxllsxlcngtm 3H 9 f blllsmkuplil calmlllsllla 3 mewmdmisfmloapisshowumwmt slide 39 See Example 87 Copyingmy mntxjam cemmsm caumusu a mulsrz mums cenmnsu DEJBJJJSS musaackupm bills sckup mugs quer hullz ackup Changing an Army s Size 39 An May s length mm variable is commit 7 that is army at migncd a constant size when they at instantiated Tn expand in army whilc W3 its original values 1 mm mmmay mawmsmanda temporary name A Copythenrigmlamaymemmy Pointmmm mmmawmmmy Magnum mule Iothemnpomymnymm Expanding the Size of an Array This code will expand the size of the calm may from 6 to 12 chums Hzmtanmam neat army double I camp x mm double 121 copy all alumnus from 091mle to Camp for 1 in 1 0 i c ceilmlladnmm 1M 5 temp Cell ill lh copy each 313mm H pom cellBills to rm array callmlls tamp temp x null Comparing Arrays for Equality a Tocompare whethct the elements of two arrays are equal 1 Maurine ifboth may haveme same W 2 Cotan each clam in the firm may with uneme museum array 0 Todothis we lluaea agvatiahlemda r loop Camparing celIBillsl to cellBillxI boolean lsEqual trim 1f 4 mlLBallalJmmh 3i callBlllsZ lenqth lsEqual file If sine an different else for in 1 I i lt callBillleenmh u numb l i i 4 Math abs collsillsluj 3311811152111 gt gt 9001 2 152mm false 1 elements ire met equal 2 39 See Example 88 Camparingmmzyw Displaying a Bar Chart We can display the data of an array graphically as a bar chart 51 Ayvlequl El 5 Awle l as 24 54 97 42 55 M 5175 29 d9 75 Angle started Each bar is drawn as a rectangle using the llRect method in the Graphics class Si2175 7 111 cell lllsh sagging magiyimua 3 BALMmm cell lllsh Llnr Dena n Arguments for the llRect Method a API for thc llkec method in the Graphic class vold 11111th in Manta mt UpperLeftY in width 1m height gt width mewmdmwnammmne For our barchatt wdnmawidlho pml 39 height thehcightfureachbuisthcuheof leumy 21mmth chatted Arguments for the llRect Method Upperheft f value a thchcightafdwbx snlm39md fmmlhcbasey value fat mm all lb ban We subtract Wymtimmmmofme windowmthcbm Uppctu x valuc mc rstbcmmaucmmtlz mgin vahmAftamdraweachharw pasi unthc minngaluefa hemxtbuby WWW wxvmWMMM thalamphntlnspacebetmm Drawing the Bar Chart int xstart 1Hm GIN first bar for 4 in 1 01 I lt cell xllsJenqih l4 glnllnsct zStaIt assan UntH 115111in BIBVIUTK 1121 mll gtllsll gt qdrawstzlmgt Doublmtc trkng call illsll xSstzrt manning 2 mom to starting a value fox next bu xStar t 43 EARWIDTH amp 5 ACE32MZHBKRS 39 See 33th 9 BarChu39tAppl gbva USing Arrays in Classes 0 In a userdme c1333 w my can be a 10m variable Wmtoamahod A amnvalug galocalvu iabkinanmhod Methods with Array Parameters a Todefmeamxthod Makes an may as a pamnetcr use this syntax accus odititr returnny whodl iamm Warm H arrayNam To de ne a method mam an my use this syntax accesamuiu aza39fy w I mthadz maei wrmtumst 2 o Topauanumy umtgmcnttoamcmodmsc the may name wimom brackets metm amsl arr ayN am lawman Error Trap Ifyou think fth brka as being part of the data type of x may then it s easy to remember that bnckctsueinclu dinth mcmodhmdcr whuemcdmmuofpammmgim bracketsmenotincludedinme1h dwls what the data itself is given Arrays as Instance Variables a Becauscarmysamobimmenameofanarrayis an object mfm Memods must be careful not to share references to instance variable with the chem Otherwise the client could airway change the may claimants using the tefaence to the my in ame vuiable See Emplex 811 E 612 Array Instance Variables A wastrth or manner that accepts an may as a parmncter should humiliate a new array for the instance We and copy the clemems from the parameter may to the instance variable may H canstwcm publlc Camacho double I hill 3 Amtzmtiazc at lth ianth a parmampar 0611131113 39 new double bills lcngthla copy parammter array m canal any fer 1n 1 O 1 lt cellullsquth I gt censulsu Minn Accessms for Arrays 0 Similarly an accessor method far the array instance vmiablc should mm a copy of the array publlc durable I gatCellEiilM 3 instantiaZd tnwpozary 3 dcuble I twwg nw doublg cullsills length C py inatzncu variable values to temp for e 15 1 t 0 i c callEillslgnqth i tempil s cgll ilxstil return copy of arrampy return temp AS Software Engineering bi Tip Sharing my xxqu with the client violam encapmla om o Toacceptwhmfamhnmwiable myasa pmmmame md hummus may md mpymeemnolmepammxytome ncwan ay 39 Similarky wrean amymam may a method shmldcopyt lmelancms oftheimtm vm39i alcmaytoampmarymxywdma refmm cmmuymny Remieving Command Line Arguments a The syntax of an array parameter for a method might look Wc vc seen it mpcamdly in tbs Mada for M main method public name mam scum the II In gt main moahess ng army as apmter hm wayholdsmemxumuifmymatmeum sandstothcpmgmnfrmmcmmdlhu Forcxample cannula line 13mm might be th naneofa lcfordxmmmme cou gmatimpl39efms Printing Command Line Arguments public SCAMC void mum String arqs System out prlntlni the number of parameters quot quot is quot 4 amulwqth M for lt wt 1 06 i lt um lsugnh 1w 3 systemmut prmtln quotutzst 1 3911 9 3759M I 0 See Exmzple a 13 Camndl nargmnngava Sequential Search a ASeqmndalScsrcbcmbensedmdmnnincif aspcci c valudthemrdl keyminanarray AWBmMWimme melmmt and commandant to leacuuhkcy If Mm icin ex of the element am mmmsthcmmhky Ifnm fmmd return 1 Bccausc1isnotavalidindexthisiugood mmvalmwm c cmm nmchkcy mnetfound inthcamy Code to Perform a Sequential Search public in find lnners int key for int i 6 L winnaxslength l if L ximxsti hay 7 return 11 Saturn 391 See Ermplu 814 and 815 Sorting an Array o Whamansz in mndomcrdcr our Sequential Snatch method needs to look a1 evcry element in the may befm disoming that the search key ism in the away This in imf cicm the large them mamincf cimt a incomes Sequential Search We could simpl r the watch by mangmgmc elements in numic 01133 which it called mung wean31012 numb automwccannsc minus mohalgnr hmmspaedupam Selection Sort In a Selection Sort we select the largest element in the array and place it at the end of the array Then we select the next largest element and put it in the next to last position in the array and so on To do this we consider the unsorted portion of the array as a subarray We repeatedly select the largest value in the current subarray and move it to the end of the subarray then consider a new subarray by eliminating the elements that are in their sorted locations We continue until the subarray has only one element At that time the array is sorted The Selection Sort Algorithm To am an array with 1 elements in ascending order 1 Cmsidexdmaelmnua Way with n elements 2 Fmduzemdexufmmawvalueinmis subway 3 Swap the Weftheelcmt with the largest valucandmcdzmemm whnposium in the subway 4 Cmsidcranzwmbmyefm m Ichant by eliminw ng me last elcmcm in 13 previous wbmy 5 szmmughdun lmL Selection Sort Example In the beginning the entire array is the unsorted subarray Unsuned subanay We swap the largest element with the last element Unsuned subanay Sum element Selection Sort Example continued Again we swap the largest and last elements Unsenee subanay Senee elements When there is only 1 unsorted element the array is completelv sorted Suned elements Swapping Values a T0 swaptwo values wede ne ampormy variablc to hold the vnlwe of one of the elements so hat we m t 109 M value during the swap To swapekmemnamd b 1 defmeawnporaymiablew 2 mignelunemawtmp 3 assign elementbmelamta 4 assigntemp wel wmla Swapping Example This code will swap claimants 3 and 6 in an in may named army mt temp 1 up 1 temp astrayLR i stag 2 arrayt3 attath ii ztnp 3 armyfe ramp ii ztnp 4 1 SeeExWIeampl tamp17 Bubble Sort The basic approach to a Bubble Sam is to make multiple passes through 111 way In each pm we We adjacent elements If anytwoadjacwdmmsuemuoiordex weput them in onkrby swapping hair vth Atthe mdofethoncmdanemhas bubbled upw ames Mum We keep making passes through the my until all mammalian inordet Bubble Sort Algorithm a To smanmayofncluncmsiuascending order weuacancstcdloop 39I heometloopexecuwwdl nms chactimuimofdmommloopmcinmloop steps through 11 the W elements ofthc may and does as allowing it cmxumcmmelamnt thmcnext alumni in the army Ifmc next chance is unmet it w the two alumna Bubble Sort Pseudocode for 1 x U to last array index 1 by 1 forjuctoIlastxruyimiax i lbyl 1f 2 consuminin el mnta Axe not in order swap the elemenu Bubble Sort Example At the beginning the array is Unsuned eiemems mum aav cauntev We compare elements 0 17 and 1 26 and find they are in the correct order so we do not swap Bubble Sort Example con39t The inner loop counter is incremented to the next element Unsuned eiemems We compare elements 1 26 and 2 5 and find they are not in the correct order so we swap them Bubble Sort Example con39t The inner loop counter is incremented to the next element Unsuned elements mum law enamel We compare elements 2 26 and 3 2 and find they are not in the correct order so we swap them The inner loop completes which ends our first pass through the array Bubble Sort Example 211d pass Unsuned subanay Sum element The largest value in the array 26 has bubbled up to its correct position We begin the second pass through the array We compare elements 0 l7 and l 5 and swap them Bubble Sort Example 211d pass Unsuned subanay Sum element Vim 5 l 17 l 2 l 25 l We compare elements 1 l7 and 2 2 and swap Unsuned subanay Sum elem m lvml lzlvlel twwlulwzlw This ends the second pass through the array The second largest element 17 has bubbled up to its correct position Bubble Sort 3rd pass We begin the last pass through the array Unsuned subanay Sum etemems Vim 5 2 17 25 I 1 2 3 We compare element 0 5 with element 1 2 and swap them Bubble Sort complete The third largest value 5 has bubbled up to its correct position l l 2 l 5 l W l 26 l l l D l 1 l 2 l 3 l Only one element remains so the array is now sorted Bubble Sort Code for 1m 1 O 1 lt arraylength 7 l l for Luz j Q j lt arraylmth v l v 1 j if t umyijl gt arrayIj 11 3 snap tbs almata wt tug crxnytj i array 4 11 urk jl arrayljl twp i f and Dune for lamp I and outer for leap See Exmnpiesamp18amp 8J9 Sorting Arrays 0f Objects a In may of objects the array elements are object mezfercnmca Thus taxman myofebjects we media 5011 the dam of the object c Usually we of the mm va ablcs of the object acts as a sort key Fcr cxmpminanem lobij mwnkey might be the mmm Example Cod to m an array of Auto objects using model asthesartkcy for in 1 t 0 i lt Harlanth 7 1 1 for mt j 0 j 4 arraylemgth w 1 7 1 3H 3 u C axuyulmmu Leanna It le 111th r o Auto temp artaytj 4 I arraym 1 attain irraYij 39 tum and if statement H and 1mm 02 190p 1 cm out r for loop Sequential Search of 21 Sorted Array a when the array is sawed we can implement a more cf cient algori nn fax a sequential seamh Ifmeswchknyisnotinmemnywecandetect that common when we nd a value that is higher than the snatch key Aummmmmnmmmm the value cram e1me mm gnaw than the scamh key Sample Code public mt searchSOEteciArraw mt key 0 i lt arrayllength for int 1 u uu n a keg 1H 1f arruyml Ray 7 return 139 return 4 I and n array mach without 1 11mm key M an element lug than the hay was 1am Binary Search A Binary Search is like the quotGuess a Numberquot game To guess a number between 1 and 100 we start with 50 halfway between the beginning number and the end number If we learn that the number is greater than 50 we immediately know the number is not 1 49 If we learn that the number is less than 50 we immediately know the number is not 51 100 We keep guessing the number that is in the middle of the remaining numbers eliminating half the remaining numbers until we find the number Binary Search a The Guess a Numberquot approach works because 1 100ma39soncd saofnumbcm TouwaBinarySemckthemymustbcsmad OmBimSemhwille ndamh keyinumniany Ifthcscamnkeyiafmndmemmmmeindcx ofthcclemwtwilhthalvam 71mm much key is not fom we mum 1 The Binary Search Algorithm We begin by comparing the middle element of the array and the search key If they are equal we found the search key and return the index of the middle element If the middle element39s value is greater than the search key then the search key cannot be found in elements with higher array indexes So we continue our search in the left half of the array If the middle element39s value is less than the search key then the search key cannot be found in elements with lower array indexes So we continue our search in the right half of the array The Binary Search Algorithm can39t a As we keep searching the mbatray we search kcepa shrinking in silo In fact the size of he submywzseamh ism in halfatevery iteration 39 Ifmcsearchkcyisnminmemaymcsubmay we search will eventually beam empty At 113 point weknowmmmw lm ndeurmh keyintheamymd reman 1 Example of a Binary Search For example we will search for the value 7 in this so ed array To begin we find the index of the center element which is 8 and we compare our search key 7 with the value 45 Binary Search Example con39t Because 7 is less than 35 we eliminate all array elements higher than our current middle element and consider elements 0 through 7 the new subarray to search The index of the center element is now 3 so we compare 7 to the value 8 Binary Search Example con39t Because 7 is less than 8 we eliminate all array elements higher than our current middle element 3 and make elements 0 through 2 the new subarray to search The index of the center element is now 1 so we compare 7 t0 the value 6 Binary Search Finding the search key Because 7 is greater than 6 we eliminate array elements lower than our current middle element 1 and make element 2 the new subarray to search The value of element 2 matches the search key so our search is successful and we return the index 2 Binary Search Example 2 This time we search for a value not found in the array 34 Again we start with the entire array and find the index of the middle element which is 8 We compare our search key 34 with the value 45 Binary Search Example 2 con39t Because 34 is less than 45 we eliminate array elements higher than our current middle element and consider elements 0 through 7 the new subarray to search The index of the center element is now 3 so we compare 34 to the value 8 Binary Search Example 2 con39t Because 34 is greater than 8 we eliminate array elements lower than our current middle element and consider elements 4 through 7 the new subarray to search The index of the center element is now 5 so we compare 34 to the value 15 Binary Search Example 2 con39t Again we eliminate array elements lower than our current middle element and make elements 6 and 7 the new subarray to search The index of the center element is now 6 so we compare 34 t0 the value 22 Binary Search 2 search key is not found Next we eliminate array elements lower than our current middle element and make element 7 the new subarray to search We compare 34 t0 the value 36 and attempt to eliminate the higher subarray which leaves an empty subarray We have determined that 32 is not in the array We return 1 to indicate an unsuccessful search Binary Search Code public In binarySaarcm 1m array int key int start 3 13 am arzayllength A 1 while sad in start 5 int mmle i smart e and 2 2 if e arraytmmm a by gt return cuddle H Rd found 9159 if lt Anaytmiddla gt key 2 and a middle 1 i search lath else start x middle 1 N match right return 1 H hay not found Using Arrays as Counters a To count multiple items w can use an array of integera Each array element isacwnm Examplc wemmtothmwadieaudcmm the umber of times each side is rollad We setupim mayors inlega munm initialized to O Fareachmllweusc mu 1 asthcindex of the my element in mm Example Code instantiate Army of counters int rolltount new int 6 roll um die WMGERDLLS times for mi 1 l L lt m 5YROLLS 1H r011 tha dig mt roll unit Hahrmdamt 6 1 H mcremnt hm coxrarspondinq manta rollcountlroll v 11M Sec Emnples 822 823 8 834


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

Jennifer McGill UCSF Med School

"Selling my MCAT study guides and notes has been a great source of side revenue while I'm in school. Some months I'm making over $500! Plus, it makes me happy knowing that I'm helping future med students with their MCAT."

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."

Parker Thompson 500 Startups

"It's a great way for students to improve their educational experience and it seemed like a product that everybody wants, so all the people participating are winning."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.