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
延伸文章資訊
- 1C/C++ bubble sort 泡沫排序法
本篇ShengYu 介紹C/C++ 中最簡單經典的泡沫排序法bubble sort,並且由C/C++ 來實作泡沫排序法bubble sort。 如果不想自己刻一個排序法可以使用現成C ...
- 2C 語言實作氣泡排序法(Bubble Sort) - Justin
C 語言實作氣泡排序法(Bubble Sort). 排序在演算法裡面算是一個很基本的問題,雖然現在各種強大的程式語言都會自帶排序演算法的函 ...
- 3[C++] 氣泡排序法(Bubble sort)
[C++] 氣泡排序法(Bubble sort). 簡單記錄一下自己的理解. 氣泡排序的意思,wiki 裡面是這麼說明: 又稱為泡沫排序,是一種簡單的排序演算法。
- 4How to Use Bubble Sort in C Programming? - Simplilearn
Bubble sort in C is a straightforward sorting algorithm that checks and swaps elements if they ar...
- 5C 語言排序演算法實作整理:泡沫排序、快速排序等 - GT Wang
若要對一連串的元素(陣列)做排序的話,有很多種實作方式,常見的排序方法有:泡沫排序法(bubble sort)、插入排序法(insertion sort)、快速排序 ...