Bubble Sort Algorithm - GeeksforGeeks
文章推薦指數: 80 %
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not ...
Skiptocontent
CoursesForWorkingProfessionalsLIVEDSALiveClassesSystemDesignJavaBackendDevelopmentFullStackLIVEExploreMoreSelf-PacedDSA-SelfPacedSDETheoryAllDevelopmentCoursesExploreMoreForStudentsLIVECompetitiveProgrammingGATELiveCourse2023DataScienceExploreMoreSelf-PacedDSA-SelfPacedCIPJAVA/Python/C++ExploreMoreSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGoLanguageHTMLCSSKotlinML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebTechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsContestsandEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblems
Comewritearticlesforusandgetfeatured
Learnandcodewiththebestindustryexperts
Getaccesstoad-freecontent,doubtassistanceandmore!
Comeandfindyourdreamjobwithus
GeeksDigest
Quizzes
GeeksCampus
GblogArticles
IDE
CampusMantri
Home
SavedVideos
Courses
GBlog
Puzzles
What'sNew?
ChangeLanguage
ArrayMatrixStringsHashingLinkedListStackQueueBinaryTreeBinarySearchTreeHeapGraphSearchingSortingDivide&ConquerMathematicalGeometricBitwiseGreedyBacktrackingBranchandBoundDynamicProgrammingPatternSearchingRandomized
RelatedArticles
▲
RelatedArticles
SortingAlgorithmsSelectionSortAlgorithmBubbleSortAlgorithmInsertionSortMergeSortQuickSortHeapSortIterativeHeapSortCountingSortRadixSortBucketSortSomeinterestingcodingproblemsonSortingSortelementsbyfrequency|Set2FindtheMinimumlengthUnsortedSubarray,sortingwhichmakesthecompletearraysortedSortnumbersstoredondifferentmachinesSortalinkedlistof0s,1sand2sAPancakeSortingProblemSortnnumbersinrangefrom0ton^2–1inlineartimeSortanarrayaccordingtotheorderdefinedbyanotherarrayCheckifanytwointervalsintersectsamongagivensetofintervalsFindthepointwheremaximumintervalsoverlapSortanalmostsortedarraywhereonlytwoelementsareswappedFindapermutationthatcausesworstcaseofMergeSortSortingVectorofPairsinC++|Set1(Sortbyfirstandsecond)Sorting2DVectorinC++|Set2(Indescendingorderbyrowandcolumn)K-thsmallestelementafterremovingsomeintegersfromnaturalnumbersSortingBigIntegersLibraryimplementationofsortingalgorithmsKnowYourSortingAlgorithm|Set1(SortingWeaponsusedbyProgrammingLanguages)Comparatorfunctionofqsort()inCKnowYourSortingAlgorithm|Set2(Introsort-C++’sSortingWeapon)std::sort()inC++STLCqsort()vsC++sort()Arrays.sort()inJavawithexamplesCollections.sort()inJavawithExamplesSomeimportanttopicsaboutsortingHoare’svsLomutopartitionschemeinQuickSortSerialSortv/sParallelSortinJavaAnInsertionSorttimecomplexityquestionLowerboundforcomparisonbasedsortingalgorithmsWhichsortingalgorithmmakesminimumnumberofmemorywrites?WhendoestheworstcaseofQuicksortoccur?CanQuickSortbeimplementedinO(nLogn)worstcasetimecomplexity?WhyQuickSortpreferredforArraysandMergeSortforLinkedLists?WhereisHeapSortusedpractically?FindmemoryconflictsamongmultiplethreadsSortingTerminologyStabilityinsortingalgorithmsTimeComplexitiesofallSortingAlgorithmsExternalSorting
SortingAlgorithmsSelectionSortAlgorithmBubbleSortAlgorithmInsertionSortMergeSortQuickSortHeapSortIterativeHeapSortCountingSortRadixSortBucketSortSomeinterestingcodingproblemsonSortingSortelementsbyfrequency|Set2FindtheMinimumlengthUnsortedSubarray,sortingwhichmakesthecompletearraysortedSortnumbersstoredondifferentmachinesSortalinkedlistof0s,1sand2sAPancakeSortingProblemSortnnumbersinrangefrom0ton^2–1inlineartimeSortanarrayaccordingtotheorderdefinedbyanotherarrayCheckifanytwointervalsintersectsamongagivensetofintervalsFindthepointwheremaximumintervalsoverlapSortanalmostsortedarraywhereonlytwoelementsareswappedFindapermutationthatcausesworstcaseofMergeSortSortingVectorofPairsinC++|Set1(Sortbyfirstandsecond)Sorting2DVectorinC++|Set2(Indescendingorderbyrowandcolumn)K-thsmallestelementafterremovingsomeintegersfromnaturalnumbersSortingBigIntegersLibraryimplementationofsortingalgorithmsKnowYourSortingAlgorithm|Set1(SortingWeaponsusedbyProgrammingLanguages)Comparatorfunctionofqsort()inCKnowYourSortingAlgorithm|Set2(Introsort-C++’sSortingWeapon)std::sort()inC++STLCqsort()vsC++sort()Arrays.sort()inJavawithexamplesCollections.sort()inJavawithExamplesSomeimportanttopicsaboutsortingHoare’svsLomutopartitionschemeinQuickSortSerialSortv/sParallelSortinJavaAnInsertionSorttimecomplexityquestionLowerboundforcomparisonbasedsortingalgorithmsWhichsortingalgorithmmakesminimumnumberofmemorywrites?WhendoestheworstcaseofQuicksortoccur?CanQuickSortbeimplementedinO(nLogn)worstcasetimecomplexity?WhyQuickSortpreferredforArraysandMergeSortforLinkedLists?WhereisHeapSortusedpractically?FindmemoryconflictsamongmultiplethreadsSortingTerminologyStabilityinsortingalgorithmsTimeComplexitiesofallSortingAlgorithmsExternalSorting
BubbleSortAlgorithm
ViewDiscussion
ImproveArticle
SaveArticle
LikeArticle
DifficultyLevel:
Easy
LastUpdated:
14Jul,2022
BubbleSortisthesimplestsortingalgorithmthatworksbyrepeatedlyswappingtheadjacentelementsiftheyareinthewrongorder.Thisalgorithmisnotsuitableforlargedatasetsasitsaverageandworst-casetimecomplexityisquitehigh.
HowBubbleSortWorks?
Consideranarrayarr[]={5,1,4,2,8}
/videojs/videoapp.min.js?ver=0.1">
ClickherefortheCompleteCourse!
FirstPass:
Bubblesortstartswithveryfirsttwoelements,comparingthemtocheckwhichoneisgreater.
(51428)–>(15428),Here,algorithmcomparesthefirsttwoelements,andswapssince5>1.
(15428)–> (14528),Swapsince5>4
(14528)–> (14258),Swapsince5>2
(14258)–>(14258),Now,sincetheseelementsarealreadyinorder(8>5),algorithmdoesnotswapthem.
SecondPass:
Now,duringseconditerationitshouldlooklikethis:
(14258)–>(14258)
(14258)–>(12458),Swapsince4>2
(12458)–>(12458)
(12458)–> (12458)
ThirdPass:
Now,thearrayisalreadysorted,butouralgorithmdoesnotknowifitiscompleted.
Thealgorithmneedsonewholepasswithoutanyswaptoknowitissorted.
(12458)–>(12458)
(12458)–>(12458)
(12458)–>(12458)
(12458)–>(12458)
Illustration:
RecommendedPractice
PunishtheStudents
TryIt!
FollowingaretheimplementationsofBubbleSort.
C++
//C++programforimplementation
//ofBubblesort
#include
延伸文章資訊
- 1Bubble Sort (With Code in Python/C++/Java/C) - Programiz
In this tutorial, you will learn about the bubble sort algorithm and its implementation in Python...
- 2[ C語言生活記事] Sorting algorithm - (1) Bubble sort | 阿鐵的碼 ...
排序演算法(1) - Bubble sort用兩個迴圈來實現,程式複雜度O( n^2 )
- 3[C++] 氣泡排序法(Bubble sort)
[C++] 氣泡排序法(Bubble sort). 簡單記錄一下自己的理解. 氣泡排序的意思,wiki 裡面是這麼說明: 又稱為泡沫排序,是一種簡單的排序演算法。
- 4C 語言排序演算法實作整理:泡沫排序、快速排序等 - GT Wang
若要對一連串的元素(陣列)做排序的話,有很多種實作方式,常見的排序方法有:泡沫排序法(bubble sort)、插入排序法(insertion sort)、快速排序 ...
- 5Bubble Sort Algorithm - GeeksforGeeks
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elem...