You are on page 1of 13

Bubble Sort Analysis

Analysis of Algorithm
Lecture # 5
Mariha Asad
Bubble Sort
for(int i=n-1; i>=1; i--)
{
It works by repeatedly swappig the
for(int j=0; j<i; j++) adjacent elements if they are in wrong
order.
{ After one iteration of outer loop one
if(arr[j] > arr[j+1]) element come its actual place(sorted
place) means largest element come at n-1
{ index.
swap(arr[j] , arr[j+1]);
}
}
}
Bubble Sort
35 18 73 40 20

18 35 73 40 20 n=5
i=4
Inner loop
18 35 73 40 20

18 35 40 73 20

18 35 40 20 73
Bubble Sort
18 35 40 20 73

18 35 40 20 73 n=5
i=3
Inner loop
18 35 40 20 73

18 35 20 40 73
Bubble Sort
18 35 20 40 73

18 35 20 40 73 n=5
i=2
Inner loop

18 20 35 40 73
Bubble Sort
18 20 35 40 73

n=5
i=1
Inner loop
Bubble Sort Analysis
for(int i=n-1; i>=1; i--) n
{ i Stmt header
for(int j=0; j<i; j++)(n*(n+1)/2) -1
{ 1 1 2
if(arr[j] > arr[j+1]) n*(n-1)/2
2 2 3
{
swap(arr[] , arr[j+1]); n*(n-1)/2 3 3 4

} n-1 n-1 n
}
}
1+ 2 +3 + …+n = sum of natural numbers = n * (n+1)/2
If n = n-1 put in formula (n-1) * ( n-1+1)/2 = n * (n-1)/2
f(n) = n + (n*(n+1)/2) -1 + n*(n-1)/2 + n*(n-1)/2
f(n) = ? O (n2) (here you are required to use the definition of big-o, big-omega, big-theta to find upper bound,
lower bound and average bound respectively)
Helping slide
i=1
inner loop statements
J=0 (1 time)
i=2
inner loop statements
J=0,1 (2 times)
i=3
inner loop statements
J=0,1,2 (3 times)
i=4
inner loop statements
J=0,1,2,3 (4 times)
Bubble Sort Analysis another method
•for(int
  i=n-1; i>=1; i--)
For(int j=0; j<i; j++)

n(n-2)/2 so it is O(n2)
Worst case for the Sorting Algorithms
When initially all the elements are in descending order and we are
required to arrange elements in ascending order or vice versa.

5 4 3 2 1

Worst case of bubble sort , selection sort and insertion sort is O(n2)
Best case for the Sorting Algorithms
When the given elements already in the sorted order
Best case of bubble and selection sort is O(n2)
Best case of insertion sort is O(n)
Assignment 1
Selection sort Running
Selection sort analysis
Selection sort upper bound by using definition of Big-oh
Thanks

You might also like