Simple Sorting Algorithms.ppt


文档分类:IT计算机 | 页数:约15页 举报非法文档有奖
1/15
下载提示
  • 1.该资料是网友上传的,本站提供全文预览,预览什么样,下载就什么样。
  • 2.下载该文档所得收入归上传者、原创者。
  • 3.下载的文档,不会出现我们的网址水印。
1/15
文档列表 文档介绍
pareeachelement(exceptthelastone)withitsneighbortotherightIftheyareoutoforder,pareeachelement(exceptthelasttwo)withitsneighbortotherightIftheyareoutoforder,pareeachelement(exceptthelastthree)withitsneighbortotherightContinueasaboveuntilyouhavenounsortedelementsontheleft2Exampleofbubblesort7285427854278542758427548275482574825478275482547824578254782457824578(done)3CodeforbubblesortpublicstaticvoidbubbleSort(int[]a){ intouter,inner; for(outer=-1;outer>0;outer--){//countingdown for(inner=0;inner<outer;inner++){//bubblingup if(a[inner]>a[inner+1]){//ifoutoforder... inttemp=a[inner];//...thenswap a[inner]=a[inner+1]; a[inner+1]=temp; } } } }4Analysisofbubblesortfor(outer=-1;outer>0;outer--){ for(inner=0;inner<outer;inner++){ if(a[inner]>a[inner+1]){ //codeforswapomitted } } }Letn==sizeofthearrayTheouterloopisexecutedn-1times(callitn,that’scloseenough)Eachtimetheouterloopisexecuted,theinnerloopisexecutedInnerloopexecutesn-1timesatfirst,linearlydroppingtojustonceOnaverage,innerloopexecutesaboutn/2timesforeachexecutionoftheouterloopIntheinnerloop,parisonisalwaysdone(constanttime),theswapmightbedone(alsoconstanttime)Resultisn*n/2*k,thatis,O(n2/2+k)=O(n2)5LoopinvariantsYourunaloopinordertochangethingsOddlyenough,whatisusuallymostimportantinunderstandingaloopisfindinganinvariant:thatis,aconditionthatdoesn’tchangeInbubblesort,weputthelargestelementsattheend,andonceweputthemthere,wedon’tmovethemagainThevariableouterstartsatthelastindexinthearrayanddecreasesto0Ourinvariantis:EveryelementtotherightofouterisinthecorrectplaceThatis,forallj>outer,ifi<j,thena[i]<=a[j]binedwithouter==0,weknowthatallelementsofthearrayareinthecorrectplace6SelectionsortGivenanarrayoflengthn,Searchelements0throughn-1andselectthesmallestSwapitwiththeelementinlocation0Searchelements1throughn-1andselectthesmallestSwapitwiththeelementinlocation1Searchelements2throughn-1andselectthesmallestSwapitwiththeelementinlocation2Searchelements3throughn-1andselectthesmallestSwapitwiththeelementin

Simple Sorting Algorithms 来自淘豆网m.daumloan.com转载请标明出处.

相关文档 更多>>
非法内容举报中心
文档信息
  • 页数15
  • 收藏数0 收藏
  • 顶次数0
  • 上传人陈潇睡不醒
  • 文件大小86 KB
  • 时间2020-08-23
最近更新