You are on page 1of 3

Bubble Sort

ALGORITHM BubbleSort(A[0..n-1]) Code


for(int i = 0 ; i <= n -2 ; i++)
for i <- 0 to n-2 do for(int j = 0 ; j<= (n - 2 - i); j++)
for j <- 0 to n-2-i do if(A[j+1] < A[j] )
if A[j+1] < A[j] {
swap A[j] and A[j+1] temp=A[j];
A[j]=A[j+1];
A[j+1]=temp; }

89 45 68 29

Outer Loop Inner Loop Array


Outer
Passes Inner Loop If condition
Loop
Condition if(A[j+1] < A[j] ) 89 45 68 29
condition
j≤n–2-i
i ≤ n-2
j=0 0≤2√ if(45 < 89) √

First
i=0
Pass

Second
i=1
Pass

i=2
Third
Pass

i=3

Dr.Hasib Data Structure and Algorithms-1 Taiz University 1


Bubble Sort
ALGORITHM BubbleSort(A[0..n-1]) Code
for(int i = 0 ; i <= n -2 ; i++)
for i <- 0 to n-2 do for(int j = 0 ; j<= (n - 2 - i); j++)
for j <- 0 to n-2-i do if(A[j+1] < A[j] )
if A[j+1] < A[j] {
swap A[j] and A[j+1] temp=A[j];
A[j]=A[j+1];
A[j+1]=temp;
}

89 45 68 90 29 34 17

Outer Loop Inner Loop Array


Outer
Passes Inner Loop If condition
Loop
Condition if(A[j+1] < A[j] ) 89 45 68 90 29 34 17
condition
j≤n–2-i
i ≤ n-2
j=0 0≤5√

j=1 1≤5√

j=2 2≤5√
First
i=0 0≤5√ j=3 3≤5√
Pass

j=4 4≤5√

j=5 5≤5√

j=6 6 ≤ 5 (false)

j=0 0≤4√
Second
i=1 1≤5√
Pass
j=1 1≤4√

Dr.Hasib Data Structure and Algorithms-1 Taiz University 2


j=2 2≤4√

j=3 3≤4√

j=4 4≤4√

j=5 5 ≤ 4 √(false)

j=0 0 ≤ 3√

j=1 1 ≤ 3√
Third
i=2 2≤5√ j=2 2 ≤ 3√
Pass
j=3 3 ≤ 3√

j=4 4 ≤ 3 (false)

j=0 0 ≤ 2√

Fourth j=1 1 ≤ 2√
i=3 3≤5√
Pass
j=2 2 ≤ 2√

j=3 3 ≤ 2(false)

j=0 0 ≤ 1√

Fifth
i=4 4≤5√ j=1 1 ≤ 1√
Pass

j=2 2 ≤ 1(false)

j=0 0 ≤ 0√
Sixth
i=5 5≤5√
Pass
j=1 1 ≤ 0(false)

6≤5
i=6
(false)

Dr.Hasib Data Structure and Algorithms-1 Taiz University 3

You might also like