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.
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
ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew?
ChangeLanguage
ArrayMatrixStringsHashingLinkedListStackQueueBinaryTreeBinarySearchTreeHeapGraphSearchingSortingDivide&ConquerMathematicalGeometricBitwiseGreedyBacktrackingBranchandBoundDynamicProgrammingPatternSearchingRandomized
RelatedArticles
▲RelatedArticlesSortingAlgorithmsSelectionSortAlgorithmBubbleSortAlgorithmInsertionSortMergeSortQuickSortHeapSortIterativeHeapSortCountingSortRadixSortBucketSortSomeinterestingcodingproblemsonSortingSortelementsbyfrequency|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?FindmemoryconflictsamongmultiplethreadsSortingTerminologyStabilityinsortingalgorithmsTimeComplexitiesofallSortingAlgorithmsExternalSortingSortingAlgorithmsSelectionSortAlgorithmBubbleSortAlgorithmInsertionSortMergeSortQuickSortHeapSortIterativeHeapSortCountingSortRadixSortBucketSortSomeinterestingcodingproblemsonSortingSortelementsbyfrequency|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?FindmemoryconflictsamongmultiplethreadsSortingTerminologyStabilityinsortingalgorithmsTimeComplexitiesofallSortingAlgorithmsExternalSortingBubbleSortAlgorithmViewDiscussion
ImproveArticle
SaveArticle
LikeArticle
DifficultyLevel:
EasyLastUpdated:
14Jul,2022BubbleSortisthesimplestsortingalgorithmthatworksbyrepeatedlyswappingtheadjacentelementsiftheyareinthewrongorder.Thisalgorithmisnotsuitableforlargedatasetsasitsaverageandworst-casetimecomplexityisquitehigh.HowBubbleSortWorks?Consideranarrayarr[]={5,1,4,2,8}
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: RecommendedPracticePunishtheStudentsTryIt!FollowingaretheimplementationsofBubbleSort. C++//C++programforimplementation //ofBubblesort#include
延伸文章資訊
- 1[演算法] 氣泡排序法(Bubble Sort):利用兩兩元素交換位置 ...
Bubble Sort 的方式是從陣列的最前面開始,一次比較陣列中兩兩相鄰的元素,然後根據大小將它們調換順序,大的移到後面:. 當我們比較過所有元素一次後, ...
- 2【Day21】[演算法]-排序Sort & 氣泡排序法Bubble Sort - iT 邦幫忙
氣泡排序法(Bubble Sort)又稱交換排序法,原理是從第一筆資料開始,逐一比較相鄰兩筆資料,如果兩筆大小順序有誤則做交換,反之則不動,接者再進行下一筆資料比較,所有 ...
- 3氣泡排序Bubble sort
Bubble sort 是最簡單的排序法之一,由於排序時每個元素會如同泡泡般,一個一個浮出序列頂部,因而得名。由於其簡單好理解,名稱又有趣,常作為第一個學習的入門排序法 ...
- 4Bubble Sort Algorithm - GeeksforGeeks
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elem...
- 5Bubble sort Algorithm - Javatpoint
Bubble sort works on the repeatedly swapping of adjacent elements until they are not in the inten...