What is Bubble Sort Algorithm? Time Complexity & Pseudocode

文章推薦指數: 80 %
投票人數:10人

The bubble sort algorithm is a reliable sorting algorithm. This algorithm has a worst-case time complexity of O(n2). The bubble sort has a ... SoftwareDevelopmentDataScience&BusinessAnalyticsAI&MachineLearningProjectManagementCyberSecurityCloudComputingDevOpsBusinessandLeadershipQualityManagementSoftwareDevelopmentAgileandScrumITServiceandArchitectureDigitalMarketingBigDataCareerFast-trackEnterpriseOtherSegmentsVideoTutorialsArticlesEbooksFreePracticeTestsOn-demandWebinarsLiveWebinarsHomeResourcesSoftwareDevelopmentDataStructureTutorialBubbleSortAlgorithm:Overview,TimeComplexity,PseudocodeandApplicationsTutorialPlaylistDataStructureTutorialOverviewArraysinDataStructures:AGuideWithExamplesLesson-1AllYouNeedtoKnowAboutTwo-DimensionalArraysLesson-2AllYouNeedtoKnowAboutaLinkedListinaDataStructureLesson-3TheCompleteGuidetoImplementaSinglyLinkedListLesson-4TheUltimateGuidetoImplementaDoublyLinkedListLesson-5TheFundamentalsforUnderstandingCircularLinkedListLesson-6TheUltimateGuideToUnderstandTheDifferencesBetweenStackAndQueueLesson-7ImplementingStacksinDataStructuresLesson-8YourOne-StopSolutionforStackImplementationUsingArrayLesson-9YourOne-StopSolutionforQueueImplementationUsingArrayLesson-10YourOne-StopSolutiontoLearnDepth-FirstSearch(DFS)AlgorithmFromScratchLesson-11YourOne-StopSolutionforStackImplementationUsingLinked-ListLesson-12TheDefinitiveGuidetoUnderstandStackvsHeapMemoryAllocationLesson-13AllYouNeedtoKnowAboutLinearSearchAlgorithmLesson-14AllYouNeedtoKnowAboutBreadth-FirstSearchAlgorithmLesson-15AOne-StopSolutionforUsingBinarySearchTreesinDataStructureLesson-16TheBestTutorialtoUnderstandTreesinDataStructureLesson-17ACompleteGuidetoImplementBinaryTreeinDataStructureLesson-18AHolisticLookatUsingAVLTreesinDataStructuresLesson-19AllYouNeedtoKnowAboutTreeTraversalinDataStructureLesson-20TheBestGuideYou’llEverNeedtoUnderstandB-TreeinDataStructureLesson-21TheBestGuideYou'llEverNeedtoUnderstandSpanningTreeinDataStructureLesson-22TheBestandEasiestWaytoUnderstandanAlgorithmLesson-23YourOne-StopSolutiontoUnderstandShellSortAlgorithmLesson-24YourOne-StopSolutiontoQuickSortAlgorithmLesson-25TheMostUsefulGuidetoLearnSelectionSortAlgorithmLesson-26EverythingYouNeedtoKnowAboutRadixSortAlgorithmLesson-27EverythingYouNeedtoKnowAbouttheCountingSortAlgorithmLesson-28EverythingYouNeedtoKnowAbouttheMergeSortAlgorithmLesson-29InsertionSortAlgorithm:One-StopSolutionThatWillHelpYouUnderstandInsertionSortLesson-30EverythingYouNeedtoKnowAbouttheBubbleSortAlgorithmLesson-31TheBestGuideYou’llEverNeedtoUnderstandBucketSortAlgorithmLesson-32YourOne-StopSolutiontoUnderstandRecursiveAlgorithminProgrammingLesson-33TheDefinitiveGuidetoUnderstandingGreedyAlgorithmLesson-34YourOne-StopSolutiontoUnderstandBacktrackingAlgorithmLesson-35TheFundamentalsoftheBellman-FordAlgorithmLesson-36YourOne-StopSolutionforGraphsinDataStructuresLesson-37TheBestGuidetoUnderstandandImplementSolutionsforTowerofHanoiPuzzleLesson-38ASimplifiedandCompleteGuidetoLearnSpaceandTimeComplexityLesson-39AllYouNeedtoKnowAbouttheKnapsackProblem:YourCompleteGuideLesson-40TheFibonacciSeries:MathematicalandProgrammingInterpretationLesson-41TheHolisticLookatLongestCommonSubsequenceProblemLesson-42TheBestArticletoUnderstandWhatIsDynamicProgrammingLesson-43AGuidetoImplementLongestIncreasingSubsequenceUsingDynamicProgrammingLesson-44AHolisticGuidetoLearnStopSolutionUsingDynamicProgrammingLesson-45OneStopSolutiontoAlltheDynamicProgrammingProblemsLesson-46UnderstandingtheFundamentalsofBinomialDistributionLesson-47Here’sAllYouNeedtoKnowAboutMinimumSpanningTreeinDataStructuresLesson-48UnderstandingtheDifferenceBetweenArrayandLinkedListLesson-49TheBestArticleOutTheretoUnderstandtheB+TreeinDataStructureLesson-50AComprehensiveLookatQueueinDataStructureLesson-51YourOne-StopSolutiontoUnderstandCoinChangeProblemLesson-52TheBestWaytoUnderstandtheMatrixChainMultiplicationProblemLesson-53YourOne-StopSolutiontoLearnFloyd-WarshallAlgorithmforUsingDynamicProgrammingLesson-54TheBestTutorialYou'llEverNeedforQueueImplementationUsingLinkedListLesson-55BubbleSortAlgorithm:Overview,TimeComplexity,PseudocodeandApplicationsLesson31of55BySoniUpadhyayLastupdatedonJul21,202254721PreviousNextTutorialPlaylistDataStructureTutorialOverviewArraysinDataStructures:AGuideWithExamplesLesson-1AllYouNeedtoKnowAboutTwo-DimensionalArraysLesson-2AllYouNeedtoKnowAboutaLinkedListinaDataStructureLesson-3TheCompleteGuidetoImplementaSinglyLinkedListLesson-4TheUltimateGuidetoImplementaDoublyLinkedListLesson-5TheFundamentalsforUnderstandingCircularLinkedListLesson-6TheUltimateGuideToUnderstandTheDifferencesBetweenStackAndQueueLesson-7ImplementingStacksinDataStructuresLesson-8YourOne-StopSolutionforStackImplementationUsingArrayLesson-9YourOne-StopSolutionforQueueImplementationUsingArrayLesson-10YourOne-StopSolutiontoLearnDepth-FirstSearch(DFS)AlgorithmFromScratchLesson-11YourOne-StopSolutionforStackImplementationUsingLinked-ListLesson-12TheDefinitiveGuidetoUnderstandStackvsHeapMemoryAllocationLesson-13AllYouNeedtoKnowAboutLinearSearchAlgorithmLesson-14AllYouNeedtoKnowAboutBreadth-FirstSearchAlgorithmLesson-15AOne-StopSolutionforUsingBinarySearchTreesinDataStructureLesson-16TheBestTutorialtoUnderstandTreesinDataStructureLesson-17ACompleteGuidetoImplementBinaryTreeinDataStructureLesson-18AHolisticLookatUsingAVLTreesinDataStructuresLesson-19AllYouNeedtoKnowAboutTreeTraversalinDataStructureLesson-20TheBestGuideYou’llEverNeedtoUnderstandB-TreeinDataStructureLesson-21TheBestGuideYou'llEverNeedtoUnderstandSpanningTreeinDataStructureLesson-22TheBestandEasiestWaytoUnderstandanAlgorithmLesson-23YourOne-StopSolutiontoUnderstandShellSortAlgorithmLesson-24YourOne-StopSolutiontoQuickSortAlgorithmLesson-25TheMostUsefulGuidetoLearnSelectionSortAlgorithmLesson-26EverythingYouNeedtoKnowAboutRadixSortAlgorithmLesson-27EverythingYouNeedtoKnowAbouttheCountingSortAlgorithmLesson-28EverythingYouNeedtoKnowAbouttheMergeSortAlgorithmLesson-29InsertionSortAlgorithm:One-StopSolutionThatWillHelpYouUnderstandInsertionSortLesson-30EverythingYouNeedtoKnowAbouttheBubbleSortAlgorithmLesson-31TheBestGuideYou’llEverNeedtoUnderstandBucketSortAlgorithmLesson-32YourOne-StopSolutiontoUnderstandRecursiveAlgorithminProgrammingLesson-33TheDefinitiveGuidetoUnderstandingGreedyAlgorithmLesson-34YourOne-StopSolutiontoUnderstandBacktrackingAlgorithmLesson-35TheFundamentalsoftheBellman-FordAlgorithmLesson-36YourOne-StopSolutionforGraphsinDataStructuresLesson-37TheBestGuidetoUnderstandandImplementSolutionsforTowerofHanoiPuzzleLesson-38ASimplifiedandCompleteGuidetoLearnSpaceandTimeComplexityLesson-39AllYouNeedtoKnowAbouttheKnapsackProblem:YourCompleteGuideLesson-40TheFibonacciSeries:MathematicalandProgrammingInterpretationLesson-41TheHolisticLookatLongestCommonSubsequenceProblemLesson-42TheBestArticletoUnderstandWhatIsDynamicProgrammingLesson-43AGuidetoImplementLongestIncreasingSubsequenceUsingDynamicProgrammingLesson-44AHolisticGuidetoLearnStopSolutionUsingDynamicProgrammingLesson-45OneStopSolutiontoAlltheDynamicProgrammingProblemsLesson-46UnderstandingtheFundamentalsofBinomialDistributionLesson-47Here’sAllYouNeedtoKnowAboutMinimumSpanningTreeinDataStructuresLesson-48UnderstandingtheDifferenceBetweenArrayandLinkedListLesson-49TheBestArticleOutTheretoUnderstandtheB+TreeinDataStructureLesson-50AComprehensiveLookatQueueinDataStructureLesson-51YourOne-StopSolutiontoUnderstandCoinChangeProblemLesson-52TheBestWaytoUnderstandtheMatrixChainMultiplicationProblemLesson-53YourOne-StopSolutiontoLearnFloyd-WarshallAlgorithmforUsingDynamicProgrammingLesson-54TheBestTutorialYou'llEverNeedforQueueImplementationUsingLinkedListLesson-55TableofContentsViewMore Thebubblesortalgorithmisareliablesortingalgorithm.Thisalgorithmhasaworst-casetimecomplexityofO(n2).ThebubblesorthasaspacecomplexityofO(1).Thenumberofswapsinbubblesortequalsthenumberofinversionpairsinthegivenarray.Whenthearrayelementsarefewandthearrayisnearlysorted,bubblesortiseffectiveandefficient. WhatIsaBubbleSortAlgorithm?   Bubblesortalgorithm,alsoknownassinkingsort,isthesimplestsortingalgorithmthatrunsthroughthelistrepeatedly,comparesadjacentelements,andswapsthemiftheyareoutoforder.  PostGraduateProgram:FullStackWebDevelopmentinCollaborationwithCaltechCTMEEnrollNow Theprocessoftraversingthelistisrepeateduntilthelistissorted.Thecomparisonsortalgorithmisnamedaftersmallerorlargerelements"bubble"atthetopofthelist.Thefollowingimagedepictsthereal-timeimplementationofBubbleSort. Bubblesortingisaccomplishedbyrecursivelycomparingadjacentelementsandsiftingtheminascendingordescendingorder. Youwillnowlookathowthebubblesortalgorithmworksafteryoubetterunderstandwhatitis. HowDoestheBubbleSortAlgorithmWork? Let'sassumeanarray. Assumeyou’reattemptingtoarrangetheelementsinascendingorder. Anarraycontainsfiveelements.Thatmeansyoumustperformfourcomparisonsforthemostsignificant(greatest)elementtobubbletothetopofthearray.  Whydoyouhavefourcomparisons? N=Thenumberofelementsinanarray N-1=Thenumberoftimecomparisonsthatoccur Therefore:5-1=4 FirstPass Comparethefirstandsecondelements,startingwiththefirstindex. Theyareswappedifthefirstelementisgreaterthanthesecond. Comparethesecondandthirdelementsnow.Iftheyarenotinthecorrectorder,swapthem. Theprecedingprocedureisrepeateduntilitreachesthefinalelement. SecondPass Theprocessisrepeatedfortheremainingiterations. Themostsignificantelementamongtheunsortedelementsisplacedattheendofeachiteration. ThirdPass Thecomparisonisperformeduptothelastunsortedelementineachiteration. FourthPass Whenalloftheunsortedelementsareplacedintheircorrectpositions,thearrayissorted. Afterunderstandinghowitworks,youwillnowlookatthealgorithmandpseudocodeofthebubblesortalgorithm. NewCourse:FullStackDevelopmentforBeginnersLearnGitCommand,Angular,NodeJS,Maven&MoreEnrollNow AlgorithmandPseudocodeforBubbleSort  AlgorithmoftheBubbleSortAlgorithm Assumethearrayisann-elementarray.Youalsoneedto assumethatthefunction"switch"thevaluesofthearrayelementsgiventoit. beginBubbleSortAlgorithm(Array) Foralltheelementsofthearray         ifarray[i]>array[i+1]             switch(array[i],array[i+!])         endif endfor returnarray endBubbleSortAlgorithm PseudocodeoftheBubbleSortAlgorithm Procedurebubblesortalgorithm(array:arrayofitems)  size=array.count;  fori=0tosize-1do:   switch=false     forj=0tosize-1do:        ifarray[j]>array{j+1}then             switch(array[j]>array[j+1])              switch=true       endif      endfor       If(notswitch),then        Break       endif     endfor endprocedurebubblesortalgorithm returnarray Continuingwiththistutorial,youwilllearnhowtooptimizeit. OptimizingBubbleSortAlgorithm Ifyoucandeterminethatthearrayissorted,youshouldhaltfurtherpasses.Itisanimprovementontheoriginalbubblesortalgorithm. Ifthereisnoswappinginaparticularpass,thearrayhasbecomesorted,andyoushouldskiptheremainingpasses.Forthis,youcanuseaflagvariablethatissettotruebeforeeachpassandissettofalsewhenswappingoccurs. voidbubbleSortAlgorithm(int*array,intele)//eleisthenumberofelementsinanarray {     for(inti=0;iarray1[j+1])           {             flag=true;              intx=array1[j+1];              array1[j+1]=array1[j];              array1[j]=x;           }        } //Swappingisnotrequiredasarrayisalreadysorted       if(!flag){          return;       }    } } Followingtheoptimizationpart,youwilllookatsomevariationsofthebubblesort. FullStackWebDeveloperCourseTobecomeanexpertinMEANStackViewCourse VariationsofBubbleSortAlgorithm Thefollowingaresomevariationsofthebubblesort: Formessagepassingsystems,odd-evensortisaparallelversionofbubblesort. Passescanbemadefromrighttoleftaswellaslefttoright.Thisismoreefficientforliststhatincludeunsorteditemsattheend. Cocktailshakersortingalternatesbetweenleftandrightpasses. Afterlookingatvariationsofthebubblesort,youwillnowlookatthecomplexityofthebubblesortalgorithm. TheComplexityoftheBubbleSortAlgorithm TheTimeComplexityoftheBubbleSortAlgorithm Bubblesortemploystwoloops:aninnerloopandanouterloop. TheinnerloopperformsO(n)comparisonsdeterministically. WorstCase Intheworst-casescenario,theouterlooprunsO(n)times. Asaresult,theworst-casetimecomplexityofbubblesortisO(nxn)=O(nxn)(n2). BestCase Inthebest-casescenario,thearrayisalreadysorted,butjustincase,bubblesortperformsO(n)comparisons. Asaresult,thetimecomplexityofbubblesortinthebest-casescenarioisO(n). AverageCase Bubblesortmayrequire(n/2)passesandO(n)comparisonsforeachpassintheaveragecase. Asaresult,theaveragecasetimecomplexityofbubblesortisO(n/2xn)=O(n/2xn)=O(n/2xn)=O(n/2xn)=O(n2). TheSpaceComplexityoftheBubbleSortAlgorithm Bubblesortrequiresonlyafixedamountofextraspacefortheflag,i,andsizevariables. Asaresult,thespacecomplexityofbubblesortisO.(1). Itisanin-placesortingalgorithm,whichmodifiestheoriginalarray'selementstosortthegivenarray. Inthistutorial,youwillseesomeofthebenefitsanddrawbacksofthebubblesort. AdvantagesofBubbleSortAlgorithm Besidesthememorythatthearrayorlistoccupies,thebubblesortrequiresverylittlememory. Thebubblesortismadeupofonlyafewlinesofcode.  Withabest-caserunningtimecomplexityofO(n),thebubblesortishelpfulindeterminingwhetherornotalistissorted.Othersortingmethodsfrequentlycyclethroughtheirentiresortingsequence,takingO(n2)orO(nlogn)timetocomplete. Thesameistruefordatasetswithonlyafewitemsthatmustbeswappedafewtimes. Now,youwilllearnsomeofthedrawbacks. DisadvantagesofBubbleSortAlgorithm Themaindisadvantageistheamountoftimeittakes.Itishighlyinefficientforlargedatasets,witharunningtimeofO(n2). Furthermore,thepresenceofturtlescansignificantlyslowthesort. Thistutorialwillconcludewithacodeimplementationofthebubblesort. FreeCourse:ProgrammingFundamentalsLearntheBasicsofProgrammingEnrollNow CodeImplementationofBubbleSortAlgorithm #include voidBucketSortAlgo(intarr[],intnum){ inti,j; intarray1[num]; for(i=0;i0;(array1[i])--){ arr[j++]=i; } } } intmain(){ intarray[100]; intnum; inti; printf("Enterthenumberofelements:"); scanf("%d",&num); printf("Enterthe%delementstobesorted:\n",num); for(i=0;i



請為這篇文章評分?