Bubble Sort (With Code in Python/C++/Java/C) - Programiz

文章推薦指數: 80 %
投票人數:10人

In this tutorial, you will learn about the bubble sort algorithm and its implementation in Python, Java, C, and C++. Bubble sort is a sorting algorithm that ... CourseIndex ExploreProgramiz Python JavaScript SQL C C++ Java Kotlin Swift C# DSA PopularTutorials QuicksortAlgorithm MergeSortAlgorithm LinkedListDataStructure HashTableDataStructure DynamicProgramming StartLearningDSA LearningPaths Challenges LearnPythonInteractively TryforFree Courses BecomeaPythonMaster BecomeaCMaster BecomeaJavaMaster ViewallCourses Python JavaScript SQL C C++ Java Kotlin Swift C# DSA PopularTutorials QuicksortAlgorithm MergeSortAlgorithm LinkedListDataStructure HashTableDataStructure DynamicProgramming StartLearningDSA AllDSATutorials Python JavaScript C C++ Java Kotlin PopularExamples Addtwonumbers Checkprimenumber Findthefactorialofanumber PrinttheFibonaccisequence Checkleapyear AllPythonExamples DSAIntroduction Whatisanalgorithm? DataStructureandTypes WhylearnDSA? AsymptoticNotations MasterTheorem DivideandConquerAlgorithm DataStructures(I) Stack Queue TypesofQueue CircularQueue PriorityQueue Deque DataStructures(II) LinkedList LinkedListOperations TypesofLinkedList HashTable HeapDataStructure FibonacciHeap DecreaseKeyandDeleteNodeOperationsonaFibonacciHeap TreebasedDSA(I) TreeDataStructure TreeTraversal BinaryTree FullBinaryTree PerfectBinaryTree CompleteBinaryTree BalancedBinaryTree BinarySearchTree AVLTree TreebasedDSA(II) BTree InsertioninaB-tree DeletionfromaB-tree B+Tree InsertiononaB+Tree DeletionfromaB+Tree Red-BlackTree Red-BlackTreeInsertion Red-BlackTreeDeletion GraphbasedDSA GraphDataStructure SpanningTree StronglyConnectedComponents AdjacencyMatrix AdjacencyList DFSAlgorithm Breadth-firstSearch BellmanFord'sAlgorithm SortingandSearchingAlgorithms BubbleSort SelectionSort InsertionSort MergeSort Quicksort CountingSort RadixSort BucketSort HeapSort ShellSort LinearSearch BinarySearch GreedyAlgorithms GreedyAlgorithm Ford-FulkersonAlgorithm Dijkstra'sAlgorithm Kruskal'sAlgorithm Prim'sAlgorithm HuffmanCoding DynamicProgramming DynamicProgramming Floyd-WarshallAlgorithm LongestCommonSequence OtherAlgorithms BacktrackingAlgorithm Rabin-KarpAlgorithm RelatedTopics SelectionSortAlgorithm InsertionSortAlgorithm ShellSortAlgorithm CountingSortAlgorithm RadixSortAlgorithm QuicksortAlgorithm BubbleSort Inthistutorial,youwilllearnaboutthebubblesortalgorithmanditsimplementationinPython,Java,C,andC++. Bubblesortisasortingalgorithmthatcomparestwoadjacentelementsandswapsthemuntiltheyarenotintheintendedorder. Justlikethemovementofairbubblesinthewaterthatriseuptothesurface,eachelementofthearraymovetotheendineachiteration.Therefore,itiscalledabubblesort. WorkingofBubbleSort Supposewearetryingtosorttheelementsinascendingorder. 1.FirstIteration(CompareandSwap) Startingfromthefirstindex,comparethefirstandthesecondelements. Ifthefirstelementisgreaterthanthesecondelement,theyareswapped. Now,comparethesecondandthethirdelements.Swapthemiftheyarenotinorder. Theaboveprocessgoesonuntilthelastelement. ComparetheAdjacentElements 2.RemainingIteration Thesameprocessgoesonfortheremainingiterations. Aftereachiteration,thelargestelementamongtheunsortedelementsisplacedattheend. PutthelargestelementattheendIneachiteration,thecomparisontakesplaceuptothelastunsortedelement. ComparetheadjacentelementsThearrayissortedwhenalltheunsortedelementsareplacedattheircorrectpositions. ThearrayissortedifallelementsarekeptintherightorderBubbleSortAlgorithm bubbleSort(array) forirightElement swapleftElementandrightElement endbubbleSort BubbleSortCodeinPython,JavaandC/C++ Python Java C C++ #BubblesortinPython defbubbleSort(array): #looptoaccesseacharrayelement foriinrange(len(array)): #looptocomparearrayelements forjinrange(0,len(array)-i-1): #comparetwoadjacentelements #change>toarray[j+1]: #swappingelementsifelements #arenotintheintendedorder temp=array[j] array[j]=array[j+1] array[j+1]=temp data=[-2,45,0,11,-9] bubbleSort(data) print('SortedArrayinAscendingOrder:') print(data) //BubblesortinJava importjava.util.Arrays; classMain{ //performthebubblesort staticvoidbubbleSort(intarray[]){ intsize=array.length; //looptoaccesseacharrayelement for(inti=0;itoarray[j+1]){ //swappingoccursifelements //arenotintheintendedorder inttemp=array[j]; array[j]=array[j+1]; array[j+1]=temp; } } publicstaticvoidmain(Stringargs[]){ int[]data={-2,45,0,11,-9}; //callmethodusingclassname Main.bubbleSort(data); System.out.println("SortedArrayinAscendingOrder:"); System.out.println(Arrays.toString(data)); } } //BubblesortinC #include //performthebubblesort voidbubbleSort(intarray[],intsize){ //looptoaccesseacharrayelement for(intstep=0;steptoarray[i+1]){ //swappingoccursifelements //arenotintheintendedorder inttemp=array[i]; array[i]=array[i+1]; array[i+1]=temp; } } } } //printarray voidprintArray(intarray[],intsize){ for(inti=0;i usingnamespacestd; //performbubblesort voidbubbleSort(intarray[],intsize){ //looptoaccesseacharrayelement for(intstep=0;steptoarray[i+1]){ //swappingelementsifelements //arenotintheintendedorder inttemp=array[i]; array[i]=array[i+1]; array[i+1]=temp; } } } } //printarray voidprintArray(intarray[],intsize){ for(inti=0;irightElement swapleftElementandrightElement swappedtoarray[j+1]: #swappingoccursifelements #arenotintheintendedorder temp=array[j] array[j]=array[j+1] array[j+1]=temp swapped=True #noswappingmeansthearrayisalreadysorted #sononeedforfurthercomparison ifnotswapped: break data=[-2,45,0,11,-9] bubbleSort(data) print('SortedArrayinAscendingOrder:') print(data) //OptimizedBubblesortinJava importjava.util.Arrays; classMain{ //performthebubblesort staticvoidbubbleSort(intarray[]){ intsize=array.length; //looptoaccesseacharrayelement for(inti=0;itoarray[j+1]){ //swappingoccursifelements //arenotintheintendedorder inttemp=array[j]; array[j]=array[j+1]; array[j+1]=temp; swapped=true; } } //noswappingmeansthearrayisalreadysorted //sononeedforfurthercomparison if(!swapped) break; } } publicstaticvoidmain(Stringargs[]){ int[]data={-2,45,0,11,-9}; //callmethodusingtheclassname Main.bubbleSort(data); System.out.println("SortedArrayinAscendingOrder:"); System.out.println(Arrays.toString(data)); } } //OptimizedBubblesortinC #include //performthebubblesort voidbubbleSort(intarray[],intsize){ //looptoaccesseacharrayelement for(intstep=0;steptoarray[i+1]){ //swappingoccursifelements //arenotintheintendedorder inttemp=array[i]; array[i]=array[i+1]; array[i+1]=temp; swapped=1; } } //noswappingmeansthearrayisalreadysorted //sononeedforfurthercomparison if(swapped==0){ break; } } } //printarray voidprintArray(intarray[],intsize){ for(inti=0;itoarray[i+1]){ //swappingoccursifelements //arenotinintendedorder inttemp=array[i]; array[i]=array[i+1]; array[i+1]=temp; swapped=1; } } //noswappingmeansthearrayisalreadysorted //sononeedoffurthercomparison if(swapped==0) break; } } //printanarray voidprintArray(intarray[],intsize){ for(inti=0;i



請為這篇文章評分?