What is Bubble Sort Algorithm? Time Complexity & Pseudocode
文章推薦指數: 80 %
Bubble sort algorithm, also known as sinking sort, is the simplest sorting algorithm that runs through the list repeatedly, compares adjacent ...
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,PseudocodeandApplicationsLesson31of55BySoniUpadhyayLastupdatedonJun27,202250685PreviousNextTutorialPlaylistDataStructureTutorialOverviewArraysinDataStructures: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
延伸文章資訊
- 1【演算】氣泡排序法- Bubble Sort - Infinite Loop
直到所有資料排序完成為止。 其原理的虛擬碼大致如下: Function bubbleSort(Type data[1..n]) Index i, j ...
- 2What is Bubble Sort Algorithm Using C,C++, Java,Python
Bubble Sort Pseudocode. We are given with an input array which is supposed to be sorted in ascend...
- 3Bubble Sort Algorithm - GeeksforGeeks
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elem...
- 4What is Bubble Sort Algorithm? Time Complexity & Pseudocode
Bubble sort algorithm, also known as sinking sort, is the simplest sorting algorithm that runs th...
- 5Bubble sort - Wikipedia
Pseudocode implementation