Loading documents preview...
Bubble Sorting
A process of arranging data in a sequence is called sorting. 30
10
50
40
60
20
Unsorted List
10
20
30
40
50
60
Sorted List
Data can be sorted in two ways, • Ascending order • Descending order 10
20
30
40
50
60
Ascending order
60
50
40
30
20
10
Descending order
Some popular sorting methods are, • Selection sort • Bubble sort • Insertion sort • Quick sort • Merge sort • Heap sort • Shell sort • Combo sort etc.
Bubble sort • Also known as the sinking sort • It works by repeatedly comparing adjacent pairs and swapping them if they are in a wrong order.
• The process continues until there no swapping is required. • This is a comparison sort because it just use the comparison to swap it’s position. • This algorithm gets it name because the “Bubbles” get top of the water by swapping it’s position with the adjacent layer.
An example for the bubble sort,
Pseudo code for Bubble sort //Input: An array A[0…n-1] of orderable elements //Output: Array A[0…n-1] sorted in ascending order for i<- 0 to n-2 do for j<- 0 to n-2-i do if A[j+1] < A[j] swap A[j] and A[j+1]
Pseudo code for Swapping //An array A[0…n-1] //Swapping i th and j th element of A[0…n-1] if i ≠ j key <- A[j] A[j] <- A[i] A[i] <- key end if
Start i 0
n-2 0 j
Swap A[j] and A[j+1]
0
n-2-i 0
j
A[j]>A[j+1] i
T End
F
Advantages of Bubble sort • Easy to understand. • Coding and implementation is easy. • Performs well when the array is almost sorted. • Performance is O(n) in a sorted array.
Disadvantage of Bubble sort • Very expensive. Both the worst case and average case contains performance of O(n2).
Run time comparison between some sorting algorithms Sorting methods
Best case
Average case
Worst case
Quick sort
nlog(n)
nlog(n)
n2
Merge sort
nlog(n)
nlog(n)
nlog(n)
Insertion sort
n
n2
n2
Selection sort
n2
n2
n2
Bubble sort
n
n2
n2
Two operation/loops will decide the time efficiency of the bubble sort, • The comparison operation (inner for loop/ contains j) • The exchange operation (outer for loop/ contains i)
Efficiency with respect to number of comparisons
Total number of comparisons in array A[0…n-1], (n-1) + (n-2) + (n-3) + … + 2 + 1 = n(n-1)/2
= n2 - n 2
The highest order of n is 2, Therefore, Bubble sort is O(n 2 ) algorithm with respect to number of comparisons.
Efficiency with respect to number of exchanges
Total number of comparisons in array A[0…n-1], (n-1) + (n-2) + (n-3) + … + 2 + 1 = n(n-1)/2
= n2 - n 2
The highest order of n is 2, Therefore, Bubble sort is O(n 2 ) algorithm with respect to number of exchanges.
References • http://thomas.baudel.name/Visualisation/VisuTri/ bubblesort.html • http://www.sorting-algorithms.com/bubble-sort • http://warp.povusers.org/SortComparison/
Thank you