Data Structure - Bubble Sort Algorithm - Tutorialspoint
文章推薦指數: 80 %
Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based algorithm in which each pair of adjacent elements is compared and the ... Home CodingGround Jobs Whiteboard Tools Business Teachwithus DataStructures&Algorithms DSA-Home DSA-Overview DSA-EnvironmentSetup Algorithm DSA-AlgorithmsBasics DSA-AsymptoticAnalysis DSA-GreedyAlgorithms DSA-DivideandConquer DSA-DynamicProgramming DataStructures DSA-DataStructureBasics DSA-ArrayDataStructure LinkedLists DSA-LinkedListBasics DSA-DoublyLinkedList DSA-CircularLinkedList Stack&Queue DSA-Stack DSA-ExpressionParsing DSA-Queue SearchingTechniques DSA-LinearSearch DSA-BinarySearch DSA-InterpolationSearch DSA-HashTable SortingTechniques DSA-SortingAlgorithms DSA-BubbleSort DSA-InsertionSort DSA-SelectionSort DSA-MergeSort DSA-ShellSort DSA-QuickSort GraphDataStructure DSA-GraphDataStructure DSA-DepthFirstTraversal DSA-BreadthFirstTraversal TreeDataStructure DSA-TreeDataStructure DSA-TreeTraversal DSA-BinarySearchTree DSA-AVLTree DSA-SpanningTree DSA-Heap Recursion DSA-RecursionBasics DSA-TowerofHanoi DSA-FibonacciSeries DSAUsefulResources DSA-QuestionsandAnswers DSA-QuickGuide DSA-UsefulResources DSA-Discussion SelectedReading UPSCIASExamsNotes Developer'sBestPractices QuestionsandAnswers EffectiveResumeWriting HRInterviewQuestions ComputerGlossary WhoisWho DataStructure-BubbleSortAlgorithm Advertisements PreviousPage NextPage Bubblesortisasimplesortingalgorithm.Thissortingalgorithmiscomparison-basedalgorithminwhicheachpairofadjacentelementsiscomparedandtheelementsareswappediftheyarenotinorder.ThisalgorithmisnotsuitableforlargedatasetsasitsaverageandworstcasecomplexityareofΟ(n2)wherenisthenumberofitems. HowBubbleSortWorks? Wetakeanunsortedarrayforourexample.BubblesorttakesΟ(n2)timesowe'rekeepingitshortandprecise. Bubblesortstartswithveryfirsttwoelements,comparingthemtocheckwhichoneisgreater. Inthiscase,value33isgreaterthan14,soitisalreadyinsortedlocations.Next,wecompare33with27. Wefindthat27issmallerthan33andthesetwovaluesmustbeswapped. Thenewarrayshouldlooklikethis− Nextwecompare33and35.Wefindthatbothareinalreadysortedpositions. Thenwemovetothenexttwovalues,35and10. Weknowthenthat10issmaller35.Hencetheyarenotsorted. Weswapthesevalues.Wefindthatwehavereachedtheendofthearray.Afteroneiteration,thearrayshouldlooklikethis− Tobeprecise,wearenowshowinghowanarrayshouldlooklikeaftereachiteration.Aftertheseconditeration,itshouldlooklikethis− Noticethataftereachiteration,atleastonevaluemovesattheend. Andwhenthere'snoswaprequired,bubblesortslearnsthatanarrayiscompletelysorted. Nowweshouldlookintosomepracticalaspectsofbubblesort. Algorithm Weassumelistisanarrayofnelements.Wefurtherassumethatswapfunctionswapsthevaluesofthegivenarrayelements. beginBubbleSort(list) forallelementsoflist iflist[i]>list[i+1] swap(list[i],list[i+1]) endif endfor returnlist endBubbleSort Pseudocode WeobserveinalgorithmthatBubbleSortcompareseachpairofarrayelementunlessthewholearrayiscompletelysortedinanascendingorder.Thismaycauseafewcomplexityissueslikewhatifthearrayneedsnomoreswappingasalltheelementsarealreadyascending. Toease-outtheissue,weuseoneflagvariableswappedwhichwillhelpusseeifanyswaphashappenedornot.Ifnoswaphasoccurred,i.e.thearrayrequiresnomoreprocessingtobesorted,itwillcomeoutoftheloop. PseudocodeofBubbleSortalgorithmcanbewrittenasfollows− procedurebubbleSort(list:arrayofitems) loop=list.count; fori=0toloop-1do: swapped=false forj=0toloop-1do: /*comparetheadjacentelements*/ iflist[j]>list[j+1]then /*swapthem*/ swap(list[j],list[j+1]) swapped=true endif endfor /*ifnonumberwasswappedthatmeans arrayissortednow,breaktheloop.*/ if(notswapped)then break endif endfor endprocedurereturnlist Implementation Onemoreissuewedidnotaddressinouroriginalalgorithmanditsimprovisedpseudocode,isthat,aftereveryiterationthehighestvaluessettlesdownattheendofthearray.Hence,thenextiterationneednotincludealreadysortedelements.Forthispurpose,inourimplementation,werestricttheinnerlooptoavoidalreadysortedvalues. ToknowaboutbubblesortimplementationinCprogramminglanguage,pleaseclickhere. PreviousPage PrintPage NextPage Advertisements
延伸文章資訊
- 1Bubble sort - Wikipedia
Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly...
- 2排序1 : 排序簡介& 氣泡排序Bubble Sort - iT 邦幫忙
排序1 : 排序簡介& 氣泡排序Bubble Sort ... 什麼是排序(Sort)? ... 的是javaScript 的Array.prototype.sort,那你知道Array.pro...
- 3Bubble Sort (With Code in Python/C++/Java/C) - Programiz
Bubble sort is a sorting algorithm that compares two adjacent elements and swaps them until they ...
- 4[演算法] 氣泡排序法(Bubble Sort):利用兩兩元素交換位置 ...
Bubble Sort 的方式是從陣列的最前面開始,一次比較陣列中兩兩相鄰的元素,然後根據大小將它們調換順序,大的移到後面:. 當我們比較過所有元素一次後, ...
- 5冒泡排序- 维基百科,自由的百科全书
冒泡排序(英語:Bubble Sort)又稱為泡式排序,是一種簡單的排序算法。它重複地走訪過要排序的數列,一次比較兩個元素,如果它們的順序錯誤就把它們交換過來。