java語言程序設(shè)計(jì)基礎(chǔ)篇課件(第6章)英文_第1頁
java語言程序設(shè)計(jì)基礎(chǔ)篇課件(第6章)英文_第2頁
java語言程序設(shè)計(jì)基礎(chǔ)篇課件(第6章)英文_第3頁
java語言程序設(shè)計(jì)基礎(chǔ)篇課件(第6章)英文_第4頁
java語言程序設(shè)計(jì)基礎(chǔ)篇課件(第6章)英文_第5頁
已閱讀5頁,還剩99頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

Chapter6Arrays1OpeningProblemReadonehundrednumbers,computetheiraverage,andfindouthowmanynumbersareabovetheaverage.2Solution3AnalyzeNumbersRunwithpreparedinputObjectivesTodescribewhyarraysarenecessaryinprogramming(§6.1).Todeclarearrayreferencevariablesandcreatearrays(§§6.2.1-6.2.2).Toinitializethevaluesinanarray(§6.2.3).Toaccessarrayelementsusingindexedvariables(§6.2.4).Todeclare,create,andinitializeanarrayusinganarrayinitializer(§6.2.5).Toprogramcommonarrayoperations(displayingarrays,summingallelements,findingminandmaxelements,randomshuffling,shiftingelements)(§6.2.6).Tosimplifyprogrammingusingthefor-eachloops(§6.2.7).ToapplyarraysintheLottoNumbersandDeckOfCardsproblems(§§6.3-6.4).Tocopycontentsfromonearraytoanother(§6.5).Todevelopandinvokemethodswitharrayargumentsandreturnvalue(§6.6–6.7).Todefineamethodwithvariable-lengthargumentlist(§6.8).Tosearchelementsusingthelinear(§6.9.1)orbinary(§6.9.2)searchalgorithm.Tosortanarrayusingtheselectionsort(§6.10.1)Tosortanarrayusingtheinsertionsortalgorithm(§6.10.2).TousethemethodsintheArraysclass(§6.11).4IntroducingArrays5Arrayisadatastructurethatrepresentsacollectionofthesametypesofdata.DeclaringArrayVariablesdatatype[]arrayRefVar;

Example:

double[]myList;datatypearrayRefVar[];//Thisstyleisallowed,butnotpreferred

Example:

doublemyList[];6CreatingArraysarrayRefVar=newdatatype[arraySize];Example:myList=newdouble[10];myList[0]referencesthefirstelementinthearray.myList[9]referencesthelastelementinthearray.7DeclaringandCreating

inOneStepdatatype[]arrayRefVar=newdatatype[arraySize];

double[]myList=newdouble[10];datatypearrayRefVar[]=new

datatype[arraySize];

doublemyList[]=newdouble[10];8TheLengthofanArrayOnceanarrayiscreated,itssizeisfixed.Itcannotbechanged.YoucanfinditssizeusingarrayRefVar.lengthForexample,myList.lengthreturns109DefaultValuesWhenanarrayiscreated,itselementsareassignedthedefaultvalueof0forthenumericprimitivedatatypes,'\u0000'forchartypes,andfalseforbooleantypes.10IndexedVariablesThearrayelementsareaccessedthroughtheindex.Thearrayindicesare0-based,i.e.,itstartsfrom0toarrayRefVar.length-1.IntheexampleinFigure6.1,myListholdstendoublevaluesandtheindicesarefrom0to9.Eachelementinthearrayisrepresentedusingthefollowingsyntax,knownasanindexedvariable:arrayRefVar[index];11UsingIndexedVariablesAfteranarrayiscreated,anindexedvariablecanbeusedinthesamewayasaregularvariable.Forexample,thefollowingcodeaddsthevalueinmyList[0]andmyList[1]tomyList[2].myList[2]=myList[0]+myList[1];12ArrayInitializersDeclaring,creating,initializinginonestep: double[]myList={1.9,2.9,3.4,3.5};Thisshorthandsyntaxmustbeinonestatement.13Declaring,creating,initializingUsingtheShorthandNotationdouble[]myList={1.9,2.9,3.4,3.5};Thisshorthandnotationisequivalenttothefollowingstatements:double[]myList=newdouble[4];myList[0]=1.9;myList[1]=2.9;myList[2]=3.4;myList[3]=3.5;14CAUTIONUsingtheshorthandnotation,youhavetodeclare,create,andinitializethearrayallinonestatement.Splittingitwouldcauseasyntaxerror.Forexample,thefollowingiswrong:double[]myList;myList={1.9,2.9,3.4,3.5};15TraceProgramwithArrayspublicclassTest{publicstaticvoidmain(String[]args){int[]values=newint[5];for(inti=1;i<5;i++){values[i]=i+values[i-1];}values[0]=values[1]+values[4];}}16Declarearrayvariablevalues,createanarray,andassignitsreferencetovaluesanimationTraceProgramwithArrayspublicclassTest{publicstaticvoidmain(String[]args){int[]values=newint[5];for(inti=1;i<5;i++){values[i]=i+values[i-1];}values[0]=values[1]+values[4];}}17ibecomes1animationTraceProgramwithArrayspublicclassTest{publicstaticvoidmain(String[]args){int[]values=newint[5];for(inti=1;i<5;i++){values[i]=i+values[i-1];}values[0]=values[1]+values[4];}}18i(=1)islessthan5animationTraceProgramwithArrayspublicclassTest{publicstaticvoidmain(String[]args){int[]values=newint[5];for(inti=1;i<5;i++){values[i]=i+values[i-1];}values[0]=values[1]+values[4];}}19Afterthislineisexecuted,value[1]is1animationTraceProgramwithArrayspublicclassTest{publicstaticvoidmain(String[]args){int[]values=newint[5];for(inti=1;i<5;i++){values[i]=i+values[i-1];}values[0]=values[1]+values[4];}}20Afteri++,ibecomes2animationTraceProgramwithArrayspublicclassTest{publicstaticvoidmain(String[]args){int[]values=newint[5];for(inti=1;i<5;i++){values[i]=i+values[i-1];}values[0]=values[1]+values[4];}}21i(=2)islessthan5animationTraceProgramwithArrayspublicclassTest{publicstaticvoidmain(String[]args){int[]values=newint[5];for(inti=1;i<5;i++){values[i]=i+values[i-1];}values[0]=values[1]+values[4];}}22Afterthislineisexecuted,values[2]is3(2+1)animationTraceProgramwithArrayspublicclassTest{publicstaticvoidmain(String[]args){int[]values=newint[5];for(inti=1;i<5;i++){values[i]=i+values[i-1];}values[0]=values[1]+values[4];}}23Afterthis,ibecomes3.animationTraceProgramwithArrayspublicclassTest{publicstaticvoidmain(String[]args){int[]values=newint[5];for(inti=1;i<5;i++){values[i]=i+values[i-1];}values[0]=values[1]+values[4];}}24i(=3)isstilllessthan5.animationTraceProgramwithArrayspublicclassTest{publicstaticvoidmain(String[]args){int[]values=newint[5];for(inti=1;i<5;i++){values[i]=i+values[i-1];}values[0]=values[1]+values[4];}}25Afterthisline,values[3]becomes6(3+3)animationTraceProgramwithArrayspublicclassTest{publicstaticvoidmain(String[]args){int[]values=newint[5];for(inti=1;i<5;i++){values[i]=i+values[i-1];}values[0]=values[1]+values[4];}}26Afterthis,ibecomes4animationTraceProgramwithArrayspublicclassTest{publicstaticvoidmain(String[]args){int[]values=newint[5];for(inti=1;i<5;i++){values[i]=i+values[i-1];}values[0]=values[1]+values[4];}}27i(=4)isstilllessthan5animationTraceProgramwithArrayspublicclassTest{publicstaticvoidmain(String[]args){int[]values=newint[5];for(inti=1;i<5;i++){values[i]=i+values[i-1];}values[0]=values[1]+values[4];}}28Afterthis,values[4]becomes10(4+6)animationTraceProgramwithArrayspublicclassTest{publicstaticvoidmain(String[]args){int[]values=newint[5];for(inti=1;i<5;i++){values[i]=i+values[i-1];}values[0]=values[1]+values[4];}}29Afteri++,ibecomes5animationTraceProgramwithArrayspublicclassTest{publicstaticvoidmain(String[]args){int[]values=newint[5];for(inti=1;i<5;i++){values[i]=i+values[i-1];}values[0]=values[1]+values[4];}}30i(=5)<5isfalse.ExittheloopanimationTraceProgramwithArrayspublicclassTest{publicstaticvoidmain(String[]args){int[]values=newint[5];for(inti=1;i<5;i++){values[i]=i+values[i-1];}values[0]=values[1]+values[4];}}31Afterthisline,values[0]is11(1+10)animationProcessingArraysSeetheexamplesinthetext.(Initializingarrayswithinputvalues)(Initializingarrayswithrandomvalues)(Printingarrays)(Summingallelements)(Findingthelargestelement)(Findingthesmallestindexofthelargestelement)(Randomshuffling)(Shiftingelements)

32Initializingarrayswithinputvaluesjava.util.Scannerinput=newjava.util.Scanner(System.in);System.out.print("Enter"+myList.length+"values:");for(inti=0;i<myList.length;i++)myList[i]=input.nextDouble();33Initializingarrayswithrandomvaluesfor(inti=0;i<myList.length;i++){myList[i]=Math.random()*100;}34Printingarraysfor(inti=0;i<myList.length;i++){System.out.print(myList[i]+"");}35Summingallelementsdoubletotal=0;for(inti=0;i<myList.length;i++){total+=myList[i];}36Findingthelargestelementdoublemax=myList[0];for(inti=1;i<myList.length;i++){

if(myList[i]>max)max=myList[i];}37Randomshuffling38ShiftingElements39EnhancedforLoop(for-eachloop)JDK1.5introducedanewforloopthatenablesyoutotraversethecompletearraysequentiallywithoutusinganindexvariable.Forexample,thefollowingcodedisplaysallelementsinthearraymyList:

for(doublevalue:myList)System.out.println(value);

Ingeneral,thesyntaxis

for(elementTypevalue:arrayRefVar){//Processthevalue}

Youstillhavetouseanindexvariableifyouwishtotraversethearrayinadifferentorderorchangetheelementsinthearray.40Problem:LottoNumbersSupposeyouplaythePick-10lotto.Eachtickethas10uniquenumbersrangingfrom1to99.Youbuyalotoftickets.Youliketohaveyourticketstocoverallnumbersfrom1to99.Writeaprogramthatreadstheticketnumbersfromafileandcheckswhetherallnumbersarecovered.Assumethelastnumberinthefileis0.41LottoNumbersRunLottoNumbersSampleDataProblem:DeckofCardsTheproblemistowriteaprogramthatpicksfourcardsrandomlyfromadeckof52cards.Allthecardscanberepresentedusinganarraynameddeck,filledwithinitialvalues0to52,asfollows:int[]deck=newint[52];//Initializecardsfor(inti=0;i<deck.length;i++)deck[i]=i;42DeckOfCardsRunProblem:DeckofCards,cont.43DeckOfCardsRunGUIDemo(pickingfourcards)Problem:DeckofCardsThisproblembuildsafoundationforfuturemoreinterestingandrealisticapplications:SeeExercise25.9.44CopyingArraysOften,inaprogram,youneedtoduplicateanarrayorapartofanarray.Insuchcasesyoucouldattempttousetheassignmentstatement(=),asfollows:

list2=list1;

45CopyingArraysUsingaloop:int[]sourceArray={2,3,1,5,10};int[]targetArray=newint[sourceArray.length];for(inti=0;i<sourceArrays.length;i++)targetArray[i]=sourceArray[i];46ThearraycopyUtilityarraycopy(sourceArray,src_pos,targetArray,tar_pos,length);Example:System.arraycopy(sourceArray,0,targetArray,0,sourceArray.length);

47PassingArraystoMethodspublicstaticvoidprintArray(int[]array){for(inti=0;i<array.length;i++){System.out.print(array[i]+"");}}

48Invokethemethodint[]list={3,1,2,6,4,2};printArray(list);InvokethemethodprintArray(newint[]{3,1,2,6,4,2});AnonymousarrayAnonymousArrayThestatementprintArray(newint[]{3,1,2,6,4,2});createsanarrayusingthefollowingsyntax:newdataType[]{literal0,literal1,...,literalk};Thereisnoexplicitreferencevariableforthearray.Sucharrayiscalledananonymousarray.49PassByValueJavausespassbyvaluetopassargumentstoamethod.Thereareimportantdifferencesbetweenpassingavalueofvariablesofprimitivedatatypesandpassingarrays.Foraparameterofaprimitivetypevalue,theactualvalueispassed.Changingthevalueofthelocalparameterinsidethemethoddoesnotaffectthevalueofthevariableoutsidethemethod.Foraparameterofanarraytype,thevalueoftheparametercontainsareferencetoanarray;thisreferenceispassedtothemethod.Anychangestothearraythatoccurinsidethemethodbodywillaffecttheoriginalarraythatwaspassedastheargument.50SimpleExamplepublicclassTest{publicstaticvoidmain(String[]args){intx=1;//xrepresentsanintvalueint[]y=newint[10];//yrepresentsanarrayofintvalues

m(x,y);//Invokemwithargumentsxandy

System.out.println("xis"+x);System.out.println("y[0]is"+y[0]);}

publicstaticvoidm(intnumber,int[]numbers){number=1001;//Assignanewvaluetonumbernumbers[0]=5555;//Assignanewvaluetonumbers[0]}}51CallStackWheninvokingm(x,y),thevaluesofxandyarepassedtonumberandnumbers.Sinceycontainsthereferencevaluetothearray,numbersnowcontainsthesamereferencevaluetothesamearray.52CallStackWheninvokingm(x,y),thevaluesofxandyarepassedtonumberandnumbers.Sinceycontainsthereferencevaluetothearray,numbersnowcontainsthesamereferencevaluetothesamearray.53HeapTheJVMstoresthearrayinanareaofmemory,calledheap,whichisusedfordynamicmemoryallocationwhereblocksofmemoryareallocatedandfreedinanarbitraryorder.54PassingArraysasArgumentsObjective:Demonstratedifferencesofpassingprimitivedatatypevariablesandarrayvariables.55TestPassArrayRunExample,cont.56ReturninganArrayfromaMethodint[]list1=newint[]{1,2,3,4,5,6};int[]list2=reverse(list1);57publicstaticint[]reverse(int[]list){int[]result=newint[list.length];

for(inti=0,j=result.length-1;i<list.length;i++,j--){result[j]=list[i];}

returnresult;}listresultTracethereverseMethodint[]list1={1,2,3,4,5,6};int[]list2=reverse(list1);58publicstaticint[]reverse(int[]list){int[]result=newint[list.length];

for(inti=0,j=result.length-1;i<list.length;i++,j--){result[j]=list[i];}

returnresult;}listresult123456000000DeclareresultandcreatearrayanimationTracethereverseMethod,[]list1=newint[]{1,2,3,4,5,6};int[]list2=reverse(list1);59publicstaticint[]reverse(int[]list){int[]result=newint[list.length];

for(inti=0,j=result.length-1;i<list.length;i++,j--){result[j]=list[i];}

returnresult;}listresult123456000000i=0andj=5animationTracethereverseMethod,[]list1=newint[]{1,2,3,4,5,6};int[]list2=reverse(list1);60publicstaticint[]reverse(int[]list){int[]result=newint[list.length];

for(inti=0,j=result.length-1;i<list.length;i++,j--){result[j]=list[i];}

returnresult;}listresult123456000000i(=0)islessthan6animationTracethereverseMethod,[]list1=newint[]{1,2,3,4,5,6};int[]list2=reverse(list1);61publicstaticint[]reverse(int[]list){int[]result=newint[list.length];

for(inti=0,j=result.length-1;i<list.length;i++,j--){result[j]=list[i];}

returnresult;}listresult123456000001i=0andj=5Assignlist[0]toresult[5]animationTracethereverseMethod,[]list1=newint[]{1,2,3,4,5,6};int[]list2=reverse(list1);62publicstaticint[]reverse(int[]list){int[]result=newint[list.length];

for(inti=0,j=result.length-1;i<list.length;i++,j--){result[j]=list[i];}

returnresult;}listresult123456000001Afterthis,ibecomes1andjbecomes4animationTracethereverseMethod,[]list1=newint[]{1,2,3,4,5,6};int[]list2=reverse(list1);63publicstaticint[]reverse(int[]list){int[]result=newint[list.length];

for(inti=0,j=result.length-1;i<list.length;i++,j--){result[j]=list[i];}

returnresult;}listresult123456000001i(=1)islessthan6animationTracethereverseMethod,[]list1=newint[]{1,2,3,4,5,6};int[]list2=reverse(list1);64publicstaticint[]reverse(int[]list){int[]result=newint[list.length];

for(inti=0,j=result.length-1;i<list.length;i++,j--){result[j]=list[i];}

returnresult;}listresult123456000021i=1andj=4Assignlist[1]toresult[4]animationTracethereverseMethod,[]list1=newint[]{1,2,3,4,5,6};int[]list2=reverse(list1);65publicstaticint[]reverse(int[]list){int[]result=newint[list.length];

for(inti=0,j=result.length-1;i<list.length;i++,j--){result[j]=list[i];}

returnresult;}listresult123456000021Afterthis,ibecomes2andjbecomes3animationTracethereverseMethod,[]list1=newint[]{1,2,3,4,5,6};int[]list2=reverse(list1);66publicstaticint[]reverse(int[]list){int[]result=newint[list.length];

for(inti=0,j=result.length-1;i<list.length;i++,j--){result[j]=list[i];}

returnresult;}listresult123456000021i(=2)isstilllessthan6animationTracethereverseMethod,[]list1=newint[]{1,2,3,4,5,6};int[]list2=reverse(list1);67publicstaticint[]reverse(int[]list){int[]result=newint[list.length];

for(inti=0,j=result.length-1;i<list.length;i++,j--){result[j]=list[i];}

returnresult;}listresult123456000321i=2andj=3Assignlist[i]toresult[j]animationTracethereverseMethod,[]list1=newint[]{1,2,3,4,5,6};int[]list2=reverse(list1);68publicstaticint[]reverse(int[]list){int[]result=newint[list.length];

for(inti=0,j=result.length-1;i<list.length;i++,j--){result[j]=list[i];}

returnresult;}listresult123456000321Afterthis,ibecomes3andjbecomes2animationTracethereverseMethod,[]list1=newint[]{1,2,3,4,5,6};int[]list2=reverse(list1);69publicstaticint[]reverse(int[]list){int[]result=newint[list.length];

for(inti=0,j=result.length-1;i<list.length;i++,j--){result[j]=list[i];}

returnresult;}listresult123456000321i(=3)isstilllessthan6animationTracethereverseMethod,[]list1=newint[]{1,2,3,4,5,6};int[]list2=reverse(list1);70publicstaticint[]reverse(int[]list){int[]result=newint[list.length];

for(inti=0,j=result.length-1;i<list.length;i++,j--){result[j]=list[i];}

returnresult;}listresult123456004321i=3andj=2Assignlist[i]toresult[j]animationTracethereverseMethod,[]list1=newint[]{1,2,3,4,5,6};int[]list2=reverse(list1);71publicstaticint[]reverse(int[]list){int[]result=newint[list.length];

for(inti=0,j=result.length-1;i<list.length;i++,j--){result[j]=list[i];}

returnresult;}listresult123456004321Afterthis,ibecomes4andjbecomes1animationTracethereverseMethod,[]list1=newint[]{1,2,3,4,5,6};int[]list2=reverse(list1);72publicstaticint[]reverse(int[]list){int[]result=newint[list.length];

for(inti=0,j=result.length-1;i<list.length;i++,j--){result[j]=list[i];}

returnresult;}listresult123456004321i(=4)isstilllessthan6animationTracethereverseMethod,[]list1=newint[]{1,2,3,4,5,6};int[]list2=reverse(list1);73publicstaticint[]reverse(int[]list){int[]result=newint[list.length];

for(inti=0,j=result.length-1;i<list.length;i++,j--){result[j]=list[i];}

returnresult;}listresult123456054321i=4andj=1Assignlist[i]toresult[j]animationTracethereverseMethod,[]list1=newint[]{1,2,3,4,5,6};int[]list2=reverse(list1);74publicstaticint[]reverse(int[]list){int[]result=newint[list.length];

for(inti=0,j=result.length-1;i<list.length;i++,j--){result[j]=list[i];}

returnresult;}listresult123456054321Afterthis,ibecomes5andjbecomes0animationTracethereverseMethod,[]list1=newint[]{1,2,3,4,5,6};int[]list2=reverse(list1);75publicstaticint[]reverse(int[]list){int[]result=newint[list.length];

for(inti=0,j=result.length-1;i<list.length;i++,j--){result[j]=list[i];}

returnresult;}listresult123456054321i(=5)isstilllessthan6animationTracethereverseMethod,[]list1=newint[]{1,2,3,4,5,6};int[]list2=reverse(list1);76publicstaticint[]reverse(int[]list){int[]result=newint[list.length];

for(inti=0,j=result.length-1;i<list.length;i++,j--){result[j]=list[i];}

returnresult;}listresult123456654321i=5andj=0Assignlist[i]toresult[j]animationTracethereverseMethod,[]list1=newint[]{1,2,3,4,5,6};int[]list2=reverse(list1);77publicstaticint[]reverse(int[]list){int[]result=newint[list.length];

for(inti=0,j=result.length-1;i<list.length;i++,j--){result[j]=list[i];}

returnresult;}listresult123456654321Afterthis,ibecomes6andjbecomes-1animationTracethereverseMethod,[]list1=newint[]{1,2,3,4,5,6};int[]list2=reverse(list1);78publicstaticint[]reverse(int[]list){int[]result=newint[list.length];

for(inti=0,j=result.length-1;i<list.length;i++,j--){result[j]=list[i];}

returnresult;}listresult123456654321i(=6)<6isfalse.Soexittheloop.animationTracethereverseMethod,[]list1=newint[]{1,2,3,4,5,6};int[]list2=reverse(list1);79publicstaticint[]reverse(int[]list){int[]result=newint[list.length];

for(inti=0,j=result.length-1;i<list.length;i++,j--){result[j]=list[i];}

returnresult;}listresult123456654321Returnresultlist2animationProblem:CountingOccurrenceofEachLetterGenerate100lowercaselettersrandomlyandassigntoanarrayofcharacters.Counttheoccurrenceofeachletterinthearray.80CountLettersInArrayRunSearchingArraysSearchingistheprocessoflookingforaspecificelementinanarray;forexample,discoveringwhetheracertainscoreisincludedinalistofscores.Searchingisacommontaskincomputerprogramming.Therearemanyalgorithmsanddatastructuresdevotedtosearching.Inthissection,twocommonlyusedapproachesarediscussed,linearsearchandbinarysearch.81LinearSearchThelinearsearchapproachcomparesthekeyelement,key,sequentiallywitheachelementinthearraylist.Themethodcontinuestodosountilthekeymatchesanelementinthelistorthelistisexhaustedwithoutamatchbeingfound.Ifamatchismade,thelinearsearchreturnstheindexoftheelementinthearraythatmatchesthekey.Ifnomatchisfound,thesearchreturns-1.82LinearSearchAnimation83641973286419732864197328641973286419732864197328333333animationKeyListFromIdeatoSolution/**Themethodforfindingakeyinthelist*/publicstaticintlinearSearch(int[]list,intkey){for(inti=0;i<list.length;i++)if(key==list[i])returni;return-1;}84int[]list={1,4,4,2,5,-3,6,2};inti=linearSearch(list,4);//returns1intj=linearSearch(list,-4);//returns-1intk=linearSearch(list,-3);//returns5TracethemethodBinarySearchForbinarysearchtowork,theelementsinthearraymustalreadybeordered.Withoutlossofgenerality,assumethatthearrayisinascendingorder.e.g.,24710114550596066697079Thebinarysearchfirstcomparesthekeywiththeelementinthemiddleofthearray.85BinarySearch,cont.Ifthekeyislessthanthemiddleelement,youonlyneedtosearchthekeyinthefirsthalfofthearray.Ifthekeyisequaltothemiddleelement,thesearchendswithamatch.Ifthekeyisgreaterthanthemiddleelement,youonlyneedtosearchthekeyinthesecondhalfofthearray.86Considerthefollowingthreecases:BinarySearch87123467891234678912346789888KeyListanimationBinarySearch,cont.88BinarySearch,cont.89BinarySearch,cont.ThebinarySearchmethodreturnstheindexoftheelementinthelistthatmatchesthesearchkeyifitiscontainedinthelist.Otherwise,itreturns-insertionpoint-1.Theinsertionpointisthepointatwhichthekeywouldbeinsertedintothelist.

90FromIdeatoSoluton/**Usebinarysearchtofindthekeyinthelist*/publicstaticintbinarySearch(int[]list,intkey){intlow=0;inthigh=list.length-1;

while(high>=low){intmid=(low+high)/2;if(key<list[mid])high=mid-1;elseif(key==list[mid])returnmid;elselow=mid+1;}

return-1-low;}91TheArrays.binarySearchMethodSincebinarysearchisfrequentlyusedinprogramming,JavaprovidesseveraloverloadedbinarySearchmethodsforsearchingakeyinanarrayofint,double,char,short,long,andfloatinthejava.util.Arraysclass.Forexample,[]list={2,4,7,10,11,45,50,59,60,66,69,70,79};System.out.println("Indexis"+java.util.Arrays.binarySearch(list,11));

char[]chars={'a','c','g','x','y','z'};System.out.println("Indexis"+java.util.Arrays.binarySearch(chars,'t'));

ForthebinarySearchmethodtowork,thearraymustbepre-sortedinincreasingorder.92Returnis4Returnis–4(insertionpointis3,soreturnis-3-1)SortingArraysSorting,likesearching,isalsoacommontaskincomputerprogramming.Manydifferentalgorithmshavebeendevelopedforsorting.Thissectionintroducestwosimple,in

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論