Time and Space complexity of Bubble Sort - OpenGenus IQ
文章推薦指數: 80 %
Θ(N^2) is the Average Case Time Complexity of Bubble Sort. The number of comparisons is constant in Bubble Sort so in average case, there is O(N^2) comparisons.
×
Home
Discussions
WriteatOpengenusIQ
×
×
Searchanything:
Interestingposts
TopCompetitiveProgrammers
UnsolvedProblemsinAlgorithms
ToppatentholdersinIndia
HowtogetDeveloperJobinJapan?
[INTERNSHIP]
STORY:MostProfitableSoftwarePatents
HowtoearnbyfilingPatents?
RichestProgrammersintheWorld
STORY:Multiplicationfrom1950to2022
PositionofIndiaatICPCWorldFinals(1999to2021)
MostDangerousLineofCode💀
AgeofAllProgrammingLanguages
HowtoearnmoneyonlineasaProgrammer?
STORY:KolmogorovN^2ConjectureDisproved
STORY:manwhorefused$1Mforhisdiscovery
STORY:ManbehindVIM
STORY:Galacticalgorithm
STORY:InventorofLinkedList
PracticeInterviewQuestions
Listof50+BinaryTreeProblems
Listof100+DynamicProgrammingProblems
Listof50+ArrayProblems
11GreedyAlgorithmProblems[MUST]
Listof50+LinkedListProblems
100+GraphAlgorithmsandTechniques
Algorithms
tutorial
3DKadane'salgorithm
StrictlyBinaryTree
CompleteBinaryTree
PreordertraversalinBinaryTree[Iterative+Recursive]
FirstKmaximumoccurringwords
BottomuptraversalofTrie
Hashing:CompleteGuide
MergeInsertionSort
Longestwordwithgivenprefixandsuffix
DataStructureusedforRecursion
Algorithmtocheckwinintic-tac-toe
Maximumareaofisland
Generate0and1with25%and75%probability
DivideandConquer
BinaryHeap
TimeandSpaceComplexityofMergeSortonLinkedList
WorstCaseofMergeSort
AsymptoticAnalysis
TimeandSpaceComplexityofCombSort
TimeandSpaceComplexityofInsertionSortonLinkedList
IterationMethodforTimeComplexity
RecurrenceTreeMethodforTimeComplexity
SubstitutionMethodforTimeComplexity
AmortizedTimeComplexity
MastertheoremforTimeComplexityanalysis
TimeandSpaceComplexityofCircularLinkedList
TimeandSpacecomplexityofBinarySearchTree(BST)
TimeandSpaceComplexityofRedBlackTree
TimeandSpaceComplexityofStoogeSort
TimeandSpaceComplexityofQueue
BubblesortvsSelectionsort
DifferentPivotselectioninQuickSort
DifferentHybridSortingAlgorithms
CombSort
HeapSort
RadixSort
CountingSort
BucketSortAlgorithm
Treesort
ShellSort
BinaryInsertionSort
InsertionSort
MergeSort
QuickSort
IntelligentDesignSortorQuantumBogoSort
Up
Getthisbook->ProblemsonArray:ForInterviewsandCompetitiveProgramming
InthisarticlewewillexplorethetimeandspacecomplexityofapopularsortingalgorithmcalledBubbleSort.Wewillalsoexploreanoptimizationofthisalgorithmandit'scomplexity.
TableofContents:
IntroductiontoBubblesort
TimeComplexityAnalysis
WorstCaseTimeComplexity
BestCaseTimeComplexity
AverageCaseTimeComplexity
SpaceComplexity
ComparisonwithotherSortingAlgorithms
IntroductiontoBubblesort
Bubblesortisanalgorithmthatsequentiallystepsthroughalistofitemsandswapsitemsiftheyaren'tinthecorrectordertillthelistissorted.
Here'sanexampleofthesortingtechniquevisualized:
Asthevisualshows,theelementsseemtobubbleuptotheircorrectpositionsinthelistandthusthenameofbubblesort.Itisalsoreferredtoascomparisonorsinkingsort.
Pseudocode
1.procedurebubbleSort(A:listofsortableitems)
2.n:=length(A)
3.fori:=0ton-1inclusivedo
4.forj:=0ton-i-1inclusivedo
5.//theelementsaren'tintherightorder
6.ifA[j]>A[j+1]then
7.//swaptheelements
8.swap(A[j],A[j+1])
9.endif
10.endfor
11.endfor
12.endprocedure
TimeComplexityAnalysis
InthisunoptimisedversiontheruntimecomplexityisΘ(N^2).Thisappliestoallthecasesincludingtheworst,bestandaveragecasesbecauseevenifthearrayisalreadysortedthealgorithmdoesn'tcheckthatatanypointandrunsthroughalliterations.Althoughthenumberofswapswoulddifferineachcase.
Thenumberoftimestheinnerloopruns
$=\sum_{j=1}^{N-i-1}1\tag{2}$
$=(N-i)\tag{1}$
Thenumberoftimestheouterloopruns
$=\sum_{i=1}^{N-1}\sum_{j=1}^{N-i-1}1=\sum_{i=1}^{N-1}N-i\tag{3}$
$=\frac{N*(N-1)}{2}\tag{4}$
Optimization
Weaddanadditionalcheckthatbreaksoutoftheouterloopifnoswapsoccurintheinnerloop.
Implementation
1.voidbubbleSort(vector
延伸文章資訊
- 1[演算法] 氣泡排序法(Bubble Sort)
時間複雜度(Time Complexity). Best Case:Ο(n). 當資料的順序恰好為由小到大時; 第一次執行後,未進行任何swap ⇒ 提前結束. Worst Case:Ο(n2).
- 2Bubble Sort – Algorithm, Source Code, Time Complexity
Bubble Sort is an easy-to-implement, stable sorting algorithm with a time complexity of O(n²) in ...
- 3Bubble Sort Algorithm - GeeksforGeeks
Worst and Average Case Time Complexity: O(N2). The worst case occurs when an array is reverse sor...
- 4Bubble sort Algorithm - Javatpoint
Average Case Complexity - It occurs when the array elements are in jumbled order that is not prop...
- 5What is Bubble Sort Algorithm? Time Complexity & Pseudocode