Bubble sort Algorithm - Javatpoint
文章推薦指數: 80 %
Bubble sort works on the repeatedly swapping of adjacent elements until they are not in the intended order. It is called bubble sort because the movement of ...
⇧SCROLLTOTOP
Home
DataStructure
C
C++
C#
Java
SQL
HTML
CSS
JavaScript
Ajax
Android
Cloud
DesignPattern
Quiz
Projects
InterviewQ
Comment
Forum
DSTutorial
DSTutorial
DSIntroduction
DSAlgorithm
AsymptoticAnalysis
DSPointer
DSStructure
DSArray
DSArray
2DArray
DSLinkedList
LinkedList
TypesofLinkedList
SinglyLinkedList
DoublyLinkedList
CircularLinkedList
CircularDoublyList
SkiplistinDS
DSStack
DSStack
ArrayImplementation
LinkedListImplementation
DSQueue
DSQueue
TypesofQueues
ArrayRepresentation
LinkedListRepresentation
CircularQueue
Deque
PriorityQueue
DSTree
DSTree
BinaryTree
BinarySearchTree
AVLTree
BTree
B+Tree
DSGraph
DSGraph
GraphImplementation
BFSAlgorithm
DFSAlgorithm
SpanningTree
DSSearching
LinearSearch
BinarySearch
DSSorting
BubbleSort
BucketSort
CombSort
CountingSort
HeapSort
InsertionSort
MergeSort
QuickSort
RadixSort
SelectionSort
ShellSort
BitonicSort
CocktailSort
CycleSort
TimSort
Differences
Linearvsnon-linear
Arrayvslinkedlist
Stackvsqueue
LinearvsCircularQueue
LinearSearchvsBinarySearch
SinglyLinkedListvsDoublyLinkedList
BinaryvsBinarySearchTree
TreevsGraph
BinarySearchtreevsAVLtree
RedBlackTreevsAVLtree
BtreevsB+tree
QuickSortvsMergeSort
BFSvsDFS
StackvsHeap
Bubblesortvs.Selectionsort
StackvsArray
FullBinaryTreevsCompleteBinaryTree
BinaryTreevsBTree
Primitivevsnon-primitivedatastructure
Datatypesvsdatastructure
Misc
TrieDataStructure
HeapDataStructure
SplayTree
FundamentaloftheDS
HashTable
PreorderTraversal
TreeTraversal
ImplementationofQueueusingStacks
ImplementationofStackusingQueue
BinomialHeap
PostorderTraversal
SparseMatrix
DetectloopinaLinkedlist
InorderTraversal
ConvertInfixtoPostfixnotation
Convertinfixtoprefixnotation
ConversionofPrefixtoPostfixexpression
ConversionofPostfixtoPrefixexpression
RemovetheloopinaLinkedList
Implementtwostacksinanarray
Reverseastackusingrecursion
Detectcycleinadirectedgraph
OptimalBinarySearchTree
PriorityQueueusingLinkedlist
BalancedBinarySearchTree
BoundaryTraversalofBinarytree
DiagonalTraversalofBinaryTree
VerticalTraversalofaBinarytree
GraphAlgorithms
TimeComplexityofSortingAlgorithms
ApplicationsofStackinDataStructure
DictionaryDataStructure
StructuredDataandUnstructuredData
ListDataStructure
TypesofTreeinDataStructure
Abstractdatatypeindatastructure
Disjointsetdatastructure
DynamicDataStructure
HashFunctioninDataStructure
CompleteBinaryTree
ThreadedBinaryTree
DiameterofBinaryTree
HeightofBinaryTree
InorderTreeTraversalwithoutStack
EnumerationofBinaryTrees
MaximumWidthofaBinaryTree
TypesofGraphinDataStructure
PrimitiveDataType
Semi-StructuredData
AdvanceDataStructures
SortanArrayof0's,1's,and2's
StockSpanProblem
ImplementationofDequebyCircularArray
RotateOperationinLinkedList
Subarraywithgivensum
Self-organizingList
UnrolledLinkedList
TypesofSparseMatrices
ApplicationofLinkedList
TopologicalSorting
TernarySearchTree
StockSpanProblem
TreapDataStructure
QuicksortonDoublyLinkedList
Inversioncount
ExpressiontreeinDS
GarbageCollectioninDS
MergeSortonDoublyLinkedList
SortStackusingRecursion
LIFOApproachindatastructure
BigONotationinDS
BinaryTreeTraversalinDS
QueueOperationsinDS
WhatisaNon-LinearDataStructure
FIFOApproachindatastructure
Whatareconnectedgraphsindatastructure
WhichPythondatastructureisimmutable
Whichdatastructureisusedbymap
Whatisiterationindatastructure
Whatarelinearsearchandbinarysearchindatastructure
HashTablevsSTLMap
Recaman'sSequence
Maximumarearectanglecreatedbyselectingfoursidesfromanarray
Maximumnumberofdistinctnodesinaroot-to-leafpath
DSMCQ
DataStructureMCQ
AdvancedDSMCQ
→next
←prev
BubblesortAlgorithm
Inthisarticle,wewilldiscusstheBubblesortAlgorithm.Theworkingprocedureofbubblesortissimplest.Thisarticlewillbeveryhelpfulandinterestingtostudentsastheymightfacebubblesortasaquestionintheirexaminations.So,itisimportanttodiscussthetopic.
Bubblesortworksontherepeatedlyswappingofadjacentelementsuntiltheyarenotintheintendedorder.Itiscalledbubblesortbecausethemovementofarrayelementsisjustlikethemovementofairbubblesinthewater.Bubblesinwaterriseuptothesurface;similarly,thearrayelementsinbubblesortmovetotheendineachiteration.
Althoughitissimpletouse,itisprimarilyusedasaneducationaltoolbecausetheperformanceofbubblesortispoorintherealworld.Itisnotsuitableforlargedatasets.Theaverageandworst-casecomplexityofBubblesortisO(n2),wherenisanumberofitems.
Bubbleshortismajorlyusedwhere-
complexitydoesnotmatter
simpleandshortcodeispreferred
Algorithm
Inthealgorithmgivenbelow,supposearrisanarrayofnelements.Theassumedswapfunctioninthealgorithmwillswapthevaluesofgivenarrayelements.
beginBubbleSort(arr)
forallarrayelements
ifarr[i]>arr[i+1]
swap(arr[i],arr[i+1])
endif
endfor
returnarr
endBubbleSort
WorkingofBubblesortAlgorithm
Now,let'sseetheworkingofBubblesortAlgorithm.
Tounderstandtheworkingofbubblesortalgorithm,let'stakeanunsortedarray.Wearetakingashortandaccuratearray,asweknowthecomplexityofbubblesortisO(n2).
Lettheelementsofarrayare-
FirstPass
Sortingwillstartfromtheinitialtwoelements.Letcomparethemtocheckwhichisgreater.
Here,32isgreaterthan13(32>13),soitisalreadysorted.Now,compare32with26.
Here,26issmallerthan36.So,swappingisrequired.Afterswappingnewarraywilllooklike-
Now,compare32and35.
Here,35isgreaterthan32.So,thereisnoswappingrequiredastheyarealreadysorted.
Now,thecomparisonwillbeinbetween35and10.
Here,10issmallerthan35thatarenotsorted.So,swappingisrequired.Now,wereachattheendofthearray.Afterfirstpass,thearraywillbe-
Now,movetotheseconditeration.
SecondPass
Thesameprocesswillbefollowedforseconditeration.
Here,10issmallerthan32.So,swappingisrequired.Afterswapping,thearraywillbe-
Now,movetothethirditeration.
ThirdPass
Thesameprocesswillbefollowedforthirditeration.
Here,10issmallerthan26.So,swappingisrequired.Afterswapping,thearraywillbe-
Now,movetothefourthiteration.
Fourthpass
Similarly,afterthefourthiteration,thearraywillbe-
Hence,thereisnoswappingrequired,sothearrayiscompletelysorted.
Bubblesortcomplexity
Now,let'sseethetimecomplexityofbubblesortinthebestcase,averagecase,andworstcase.Wewillalsoseethespacecomplexityofbubblesort.
1.TimeComplexity
Case
TimeComplexity
BestCase
O(n)
AverageCase
O(n2)
WorstCase
O(n2)
BestCaseComplexity-Itoccurswhenthereisnosortingrequired,i.e.thearrayisalreadysorted.Thebest-casetimecomplexityofbubblesortisO(n).
AverageCaseComplexity-Itoccurswhenthearrayelementsareinjumbledorderthatisnotproperlyascendingandnotproperlydescending.TheaveragecasetimecomplexityofbubblesortisO(n2).
WorstCaseComplexity-Itoccurswhenthearrayelementsarerequiredtobesortedinreverseorder.Thatmeanssupposeyouhavetosortthearrayelementsinascendingorder,butitselementsareindescendingorder.Theworst-casetimecomplexityofbubblesortisO(n2).
2.SpaceComplexity
SpaceComplexity
O(1)
Stable
YES
ThespacecomplexityofbubblesortisO(1).Itisbecause,inbubblesort,anextravariableisrequiredforswapping.
ThespacecomplexityofoptimizedbubblesortisO(2).Itisbecausetwoextravariablesarerequiredinoptimizedbubblesort.
Now,let'sdiscusstheoptimizedbubblesortalgorithm.
OptimizedBubblesortAlgorithm
Inthebubblesortalgorithm,comparisonsaremadeevenwhenthearrayisalreadysorted.Becauseofthat,theexecutiontimeincreases.
Tosolveit,wecanuseanextravariableswapped.Itissettotrueifswappingrequires;otherwise,itissettofalse.
Itwillbehelpful,assupposeafteraniteration,ifthereisnoswappingrequired,thevalueofvariableswappedwillbefalse.Itmeansthattheelementsarealreadysorted,andnofurtheriterationsarerequired.
Thismethodwillreducetheexecutiontimeandalsooptimizesthebubblesort.
Algorithmforoptimizedbubblesort
bubbleSort(array)
n=length(array)
repeat
swapped=false
fori=1ton-1
ifarray[i-1]>array[i],then
swap(array[i-1],array[i])
swapped=true
endif
endfor
n=n-1
untilnotswapped
endbubbleSort
ImplementationofBubblesort
Now,let'sseetheprogramsofBubblesortindifferentprogramminglanguages.
Program:WriteaprogramtoimplementbubblesortinClanguage.
#include
voidprint(inta[],intn)//functiontoprintarrayelements
{
inti;
for(i=0;i
Output
Program:WriteaprogramtoimplementbubblesortinPHP.
";
printArray($a);
for($i=0;$i<5;$i++)
{
for($j=0;$j<5;$j++)
{
if($a[$i]Aftersortingarrayelementsare-
";
printArray($a);
?>
Output
Program:Writeaprogramtoimplementbubblesortinpython.
a=[35,10,31,11,26]
print("Beforesortingarrayelementsare-")
foriina:
print(i,end="")
foriinrange(0,len(a)):
forjinrange(i+1,len(a)):
ifa[j]
延伸文章資訊
- 1Data Structure - Bubble Sort Algorithm - Tutorialspoint
Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based algorithm i...
- 2冒泡排序- 维基百科,自由的百科全书
冒泡排序(英語:Bubble Sort)又稱為泡式排序,是一種簡單的排序算法。它重複地走訪過要排序的數列,一次比較兩個元素,如果它們的順序錯誤就把它們交換過來。
- 3氣泡排序Bubble sort
Bubble sort 是最簡單的排序法之一,由於排序時每個元素會如同泡泡般,一個一個浮出序列頂部,因而得名。由於其簡單好理解,名稱又有趣,常作為第一個學習的入門排序法 ...
- 4[演算法] 氣泡排序法(Bubble Sort):利用兩兩元素交換位置 ...
Bubble Sort 的方式是從陣列的最前面開始,一次比較陣列中兩兩相鄰的元素,然後根據大小將它們調換順序,大的移到後面:. 當我們比較過所有元素一次後, ...
- 5Bubble 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 ...