Python Program for Bubble Sort - GeeksforGeeks
文章推薦指數: 80 %
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. Python3 ... 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 ▲RelatedArticlesWhyisBinarySearchpreferredoverTernarySearch?TernarySearchStoogeSortPythonProgramforStoogeSortPythonProgramforInsertionSortPythonProgramforSelectionSortPythonProgramforBubbleSortBubbleSortAlgorithmProgramtocheckifagivennumberisLucky(alldigitsaredifferent)LuckyNumbersWriteaprogramtoaddtwonumbersinbase14BabylonianmethodforsquarerootSquarerootofanintegerFindsquarerootofnumberuptogivenprecisionusingbinarysearchBinarySearchLinearSearchLinearSearchvsBinarySearchInterpolationsearchvsBinarysearchInterpolationSearchExponentialSearchPythonprogramtoconvertalisttostringDefaultdictinPythonPython|SplitstringintolistofcharactersHowtoprintwithoutnewlineinPython?Python|GetdictionarykeysasalistPythonprogramtocheckwhetheranumberisPrimeornotPython|ConvertalisttodictionaryPythonProgramforFibonaccinumbersPythonProgramforBinarySearch(RecursiveandIterative)Python|ConvertstringdictionarytodictionaryWhyisBinarySearchpreferredoverTernarySearch?TernarySearchStoogeSortPythonProgramforStoogeSortPythonProgramforInsertionSortPythonProgramforSelectionSortPythonProgramforBubbleSortBubbleSortAlgorithmProgramtocheckifagivennumberisLucky(alldigitsaredifferent)LuckyNumbersWriteaprogramtoaddtwonumbersinbase14BabylonianmethodforsquarerootSquarerootofanintegerFindsquarerootofnumberuptogivenprecisionusingbinarysearchBinarySearchLinearSearchLinearSearchvsBinarySearchInterpolationsearchvsBinarysearchInterpolationSearchExponentialSearchPythonprogramtoconvertalisttostringDefaultdictinPythonPython|SplitstringintolistofcharactersHowtoprintwithoutnewlineinPython?Python|GetdictionarykeysasalistPythonprogramtocheckwhetheranumberisPrimeornotPython|ConvertalisttodictionaryPythonProgramforFibonaccinumbersPythonProgramforBinarySearch(RecursiveandIterative)Python|ConvertstringdictionarytodictionaryPythonProgramforBubbleSortViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: EasyLastUpdated: 13Jun,2022BubbleSortisthesimplestsortingalgorithmthatworksbyrepeatedlyswappingtheadjacentelementsiftheyareinthewrongorder. Python3#PythonprogramforimplementationofBubbleSort defbubbleSort(arr): n=len(arr) #optimizecode,soifthearrayisalreadysorted,itdoesn'tneed #togothroughtheentireprocess swapped=False #Traversethroughallarrayelements foriinrange(n-1): #range(n)alsoworkbutouterloopwill #repeatonetimemorethanneeded. #Lastielementsarealreadyinplace forjinrange(0,n-i-1): #traversethearrayfrom0ton-i-1 #Swapiftheelementfoundisgreater #thanthenextelement ifarr[j]>arr[j+1]: swapped=True arr[j],arr[j+1]=arr[j+1],arr[j] ifnotswapped: #ifwehaven'tneededtomakeasingleswap,we #canjustexitthemainloop. return #Drivercodetotestabovearr=[64,34,25,12,22,11,90] bubbleSort(arr) print("Sortedarrayis:")foriinrange(len(arr)): print("%d"%arr[i],end="")OutputSortedarrayis: 11122225346490TimeComplexity: O(n2).AuxiliarySpace:O(1).PleaserefercompletearticleonBubbleSortformoredetails! Python3defbubblesort(elements): swapped=False #Loopingfromsizeofarrayfromlastindex[-1]toindex[0] forninrange(len(elements)-1,0,-1): foriinrange(n): ifelements[i]>elements[i+1]: swapped=True #swappingdataiftheelementislessthannextelementinthearray elements[i],elements[i+1]=elements[i+1],elements[i] ifnotswapped: #exitingthefunctionifwedidn'tmakeasingleswap #meaningthatthearrayisalreadysorted. return elements=[39,12,18,85,72,10,2,18] print("Unsortedlistis,")print(elements)bubblesort(elements)print("SortedArrayis,")print(elements)OutputUnsortedlistis, [39,12,18,85,72,10,2,18] SortedArrayis, [2,10,12,18,18,39,72,85]TimeComplexity: O(n2).Howeverinpractice,thisoptimizedversionmighttakelesstimeaswhenarraygetssorted,functionwouldreturn.AuxiliarySpace:O(1).MyPersonalNotes arrow_drop_upSave LikePreviousPythonProgramforSelectionSortNext BubbleSortAlgorithmRecommendedArticlesPage:01,Apr1904,Mar2114,Dec2017,Jan2002,Feb1402,Feb1402,Feb1415,Feb1701,Feb1415,Feb1706,Oct2020,Feb1629,May1908,Feb2115,Feb1722,Jan2105,Apr1922,Jun1702,Feb1403,Sep1828,Jun1628,Jun1628,Jun1611,Jun17ArticleContributedBy:GeeksforGeeksVotefordifficultyCurrentdifficulty: EasyEasy Normal Medium Hard ExpertImprovedBy:banvariguptajhinjhakpriyampatel9911surinderdawra388surindertarika1234satyam00soamartyaghoshgfgtalktoanmolchandramauliguptachArticleTags:BubbleSortpythonsorting-exercisesPythonProgramsSortingPracticeTags:SortingReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsWhat'sNewViewDetailsViewDetailsViewDetailsImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register
延伸文章資訊
- 1Python Program for Bubble Sort - GeeksforGeeks
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elem...
- 2How to sort dictionary by value in Python? - TutorialsTeacher
We can employ a simple bubble sort to arrange tuples according to the mark component, as shown be...
- 3How to sort dictionary by value in Python? | Felxiple Tutorials
- 4Q. Write a program to sort a dictionary's keys using bubble sort ...
Q. Write a program to sort a dictionary's keys using bubble sort and produce the sorted keys ... ...
- 5python bubble sort Code Example
def bubbleSort(lis): length = len(lis) for i in range(length): for j in range(length - i): a = li...