What is Bubble Sort Algorithm? Time Complexity & Pseudocode
文章推薦指數: 80 %
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;i
延伸文章資訊
- 1The Bubble Sort Algorithm - SparkNotes
- 2Bubble Sort Algorithm - Studytonight
Also, the best case time complexity will be O(n), it is when the list is already sorted. Followin...
- 3Bubble sort Algorithm - Javatpoint
Best Case Complexity - It occurs when there is no sorting required, i.e. the array is already sor...
- 4Why does bubble sort have O(n) time complexity in the best ...
Best Case: The best case would be if the list were already sorted. Now think best case as list is...
- 5Bubble Sort Algorithm - GeeksforGeeks
The worst-case condition for bubble sort occurs when elements of the array are arranged in decrea...