Programming MethodologyLecture23.docx
《Programming MethodologyLecture23.docx》由会员分享,可在线阅读,更多相关《Programming MethodologyLecture23.docx(14页珍藏版)》请在冰豆网上搜索。
![Programming MethodologyLecture23.docx](https://file1.bdocx.com/fileroot1/2023-1/22/7dc4bb11-6e61-4432-823c-2826cb11ca59/7dc4bb11-6e61-4432-823c-2826cb11ca591.gif)
ProgrammingMethodologyLecture23
ProgrammingMethodology-Lecture23
Instructor(MehranSahami):
Sowelcometothe106AlecturejustbeforeThanksgiving.Ithoughtattendancemightnotbespectaculartoday.Peoplearestillfilteringin,butit抯goodtoseesomanyofyouhere,though.I抦suresomeofyouhavealreadyheadedhome.
YoumaybewonderingwhoIam.Iwouldhavethoughtbeforewegotbackmid-quarterevaluationsthatyoustoodachanceofrecognizingmeastheTAofyourclass,butthecommentofmorethanhalfofthepeoplewhorespondedtothequestionofhowisBendoingwas,揑don抰knowBen.I抳eneverinteractedwithBen.SoIassumehe抯doingagreatjob.?
Mostofyoujumpedtothatconclusion.But?
soIsortofchasedatthis,butnotmuch.Irealize,though,thatIwouldenjoytheopportunitytodevelopalittlemoreexposure.AndsoMaronandIdecidedtoswitchrolesfortoday.Infact,he抯makingcopiesaswespeak,andthere抯goingtobeonehandoutthat抯sortofpertinenttowhatyou抣lbedoingfor[inaudible]thenextassignment.Andheshouldbebackanytime,butIcertainlycan抰blamehimforbeing?
runningalittlelatesinceIwassupposedtomakethecopiesbeforeclassmyself.Soanyway,inmycapacityasMaron,Idon抰hopetobeasspontaneousorasfunnyasheis,butIdohopetotalkaboutsomethingthatisalittlebitoffofthesortofchartedpathofCS106A抯curriculum.
Soonewayofdescribingthethingsthatyou抮elearningin106Aisthatyou抮elearninghowtotakethewaysthatyoualreadyknowofdoingthingsthatmaytakeyousometimeandmaybeerror-proneinthedoingofthemandtellacomputerpreciselyhowtodothemsothatyoureapthebenefitsofamachinebeingabletoexecutethoseinstructions.Andthey抣lbefaster.There抣lbefewererrorsaslongasyougettheinstructionsrightinthefirstplace.Andthat抯gottobeanexhilaratingfeeling.It抯gottobeempowering,oratleastitwaswhenIwassittinginyourplaceasafreshman,toknowthat,allofasudden,ifyouhaveagoodidea?
ifyoucancomeupwithaprocedureforsolvingaproblemthatyou抳ealwayshadandtellacomputerhowtodoit,thenthecomputerwillbeabletodothatoverandoverandoveragain.Allright?
Sothat抯106Ainanutshell.Soit抯sortof?
it抯notaperfectmetaphor.Whatdoesitmeantorunbreakoutbyhands?
Idon抰know.
SowhatI?
thedistinctionI抦tryingtomakebetweenwhatyou抳ebeenlearningsofarandwhatyouwilllearn,hopefully,inthislecture?
andcertainlyifyougoontoCS106B?
isthattherearethingsthatcomputerscandothatyoucouldn抰possiblyhavesimulatedbyhand.Computerscanhandlesomuchmoredatathanyoucouldevermanagetosortthroughonyourownmanuallythatit抯worthyou抮elearningabitabouthowtomakethemdothat?
howtothinkaboutinstructingacomputertodosomethingthatyoucouldn抰possiblyhavedone.Sotoday,we抮egoingtotalkabouttwoofthemostimportantkindsofthoseproblemsincomputerscience,andI抦goingtostopjusttalkingatyouandshowyousomeexamplesinasecond.Butthosetwotopicsaresearchingandsorting.Howdoyoufindsomethinginasetofthingsthatyouhave?
Andhow,ifyoucouldimposesomestructureonthatset,wouldyoubothfinditmorequickly,and?
IguessIgotaheadofmyself?
howwouldyougoaboutimposingthesortofstructurethatwouldhelpyoufinditmorequickly?
Allright.SoifI抦seemingtoramble,thatstopsnow.
Sosearchingandsorting?
Isaytheyareimportant,andIhopeyoubelieveme,andyouthinkthatforthatreason,it抯worthtalkingaboutforanentirelecture.Buttheyreallyarejustawayofgettingtotalkaboutsomethingalittledeeper,whichisthisconceptofalgorithmicefficiencythatwehaven抰saidmuchaboutintheclasssofar.Sothat抯thethirdpartofthistwo-partlecture.What抯thedealwithsearching?
Well,searchingdoesn抰quitefitthemoldassomethingyoucouldn抰dobyhand.Youfindthingsallthetime.Chapter12ofthebooklooksattwooperationsofthesearchingandsorting.Thisisprettygeneric.Allright.Sosearchingissimpler.Youcandefineasearchproblem?
sayyouhaveanarrayorsomeothercollectionofthings,andyouhavesomethingyouwanttofind.Thetypicalwaythisisdoneisthatyouwanttofindtheindexintothearray?
wherethatelementwas?
or,inamoregenericcase,youwanttofindoutifthatelementiseveninthearray.Soyouwanttohavesomewayofdeterminingthatitwasn抰actuallyfound.
Andthatmaybeallyoucareabout.Itmaybethecasethat,ifthesearchroutinereturnsanythingotherthannegativeone,youdon抰actuallycarewhatitsvaluewas.Butweadopt?
Iwilladopttheconventionforthislecturethatifyoudon抰findwhatyou抮esearchingfor,thenthemethodthatyouwrotetodothesearchshouldreturnanegativevaluesincethat抯notavalidindexintothearray.Allright.Soifyouhaveasetofthingsthatyou抮etryingtosearchthrough,theeasiestwayofdoingthatisjusttolookatallofthemandseeifeachone,inturn,iswhatyou抮elookingfor.That抯calledalinearsearchbecause,tosortofpre-figurewhatwe抮egoingtotalkaboutattheendofthelecture,thenumberofoperationsyouhavetodotofindtheelementthatyou抮elookingforislinearlyproportionaltothenumberofelementsthatyouhadtobeginwith.Nowitmaynotbeobviousrightnowthatthere抯somethingbetterthatyoucando,andwithanarbitrarysetofdata,thereisnotanythingbetterthatyoucando.ButthisprocedurethatI抳ewrittenuphereisanimplementationofwhatyoualreadycouldhavewritten?
aprocedureforfindinganelementinanarrayofintegers.
Sothere抯nothingverytrickyaboutthis.Ifithadbeenastring,youmighthaveevenavoidedhavingtowritethefunctionandcalleditsomethinglike,揑ndexof?
withacharacter.Andinsideof揑ndexof?
thoughyoudon抰havetowritethecode,itwouldhavehadafourloopthatiteratedovereachofthecharactersofthestring,testedeachoneforqualitywiththekeythatyouwerelookingforandthen,presumingitfoundonethatequaledthatcharacter?
orinthiscase,thatinteger?
itwouldreturntheindexofit.Andifthefourloopcompletes,thenyoumustnothaveexaminedanyelementsthatmatched,andsoyoureturnnegativeone.Okay?
Sohere抯asimulationofhowthatwouldwork,althoughthe?
leavingnothingtotheimaginationhere,thisisprettyeasytosortofenvision.
Sowehavethisarrayofprimes,andithas17init.Sowearegoingtoexpecttofindthatthislinearsearchshouldn抰returnnegativeone.Butthesecondone,we抮elookingfor27?
whichsortoflooksprime,butofcourse,it抯notbecauseit抯ninetimesthree.Allright?
Okay.Sowecalledlinearsearch,andhere抯ournewstatframe,whichhasthelocalvariablesIandtheparametersPandarrayinit.ThisissortofEricRobert抯?
whowrotethetextbooks?
wayofdisplayingtheexecutionmodelofJAVA.Allright?
Sowe抮ejustloopingoverit,andwe抮etestingasIequalszeroandthenoneandthentwoandthenthreeandfour,five,six?
whereshouldwefindit?
Well,wewerelookingforseven?
no.Rightnow,we抮elookingfor27.Sowe抮ejustgonnagotothe?
Ithinktherewasaproblemwiththewaythat?
well,anyway.Theconsolehereprintsoutthat,indeed,wefound17atpositionsix.TheremayhavebeenaproblemconvertingPowerPointslidestoKeynoteslides,soIapologizeforthesortofshakinessoftheseanimations.Butthecontentoftheslidesshouldbeadequate.Cool.
Allright.Sonowwe抮einoursecondcalledlinearsearch,andtheonlythingthat抯changedatthispointfromthebeginningofthefirstcalledwasthatthekeyisdifferent.SoIisstillgonnastartatzero,andit抯stillgonnaiterateoverallofthepositionsofthearray.Butwe抮egonnagothroughtheentirearray,whichmeansgoingallthewayuptotenwhereIisnolongerlessthanten.Andwedidn抰find27anywhere.SoIhopethisisallfairlyclear.Butthesearetheresultsthatyouwouldhaveexpected.Sowefoundthepositionof17,andthenwelookedfor27butdidn抰finditandreturnednegativeone.Cool.
Howmanypeoplethinktheycouldhavewrittenthatintheirsleep?
Thatthatwastoomuchtimetospendonsuchasimpleidea?
Allright.Well,itgetsmoreinterestingfromhereonout,but?
sotalktome.Whatistheproblemwithlinearsearch?
Student:
Ittakesalotoftime.
Instructor(MehranSahami):
Ittakesalotoftime,right?
Ittakesasmuchtimeasyouhaveelements.SoifIaskedaquestion,whichwas?
ifIknewtheSUIDnumberofoneofyouintheroom,andIasked,揑sthisyourSUIDnumber?
Andyousay,揘o.?
AndIaskyou,揑s05179164yourSUIDnumber?
?
Isityours?
Bekind.Tellmeit抯yours.
Student:
[Inaudible].
Instructor(MehranSahami):
It抯not.Soitactuallyturnsoutthatit抯mine,soIwouldhavehadtosearchtheentireroombeforeIfinallygotbacktomyselfifIdidn抰makethatshortcut.Okay.
Soanotherillustrationofwhatisreallyaverysimpleidea?
thatifyou抮eforcedtolookatalloftheelementsthatyouaresearchingamong,thenthat抯badinandofitselfifyoucoulddobetter.Sowe抣lseeifwecandobetter,buthereisaratherlargerdataset?
286areacodes?
thethree-digitnumbersthatcomebeforetherestofthesevendigitsinyourphonenumbers.
Butwe抮etryingtofind650,whichisthiscounty抯areacode.Sohere抯alargerarray.Whatwouldhappenifweweresearchinginthis?
Well,itdepends.Ifwehaveafastcomputer,itmaynotmatter.Theseare?
there抯onlyabout300numbershere,anddoingsomething300timesissomethingthatcomputersarereasonablygoodat.
ButIthoughtI抎puttogetherthissortofcompellingexampleofwhythiscanbecomeabad