56% found this document useful (9 votes)
41K views

BubbleSort Flowchart

Bubble sort is a sorting algorithm that iterates through an array and compares adjacent elements, swapping them if they are in the wrong order. It makes multiple passes through the array, iterating from the first element to the last, comparing and swapping adjacent elements until no swaps are needed, indicating the array is fully sorted. The algorithm has a time complexity of O(n^2) as each pass through the array requires n comparisons and there are n total passes needed in the worst case.

Uploaded by

blackcoder41
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
56% found this document useful (9 votes)
41K views

BubbleSort Flowchart

Bubble sort is a sorting algorithm that iterates through an array and compares adjacent elements, swapping them if they are in the wrong order. It makes multiple passes through the array, iterating from the first element to the last, comparing and swapping adjacent elements until no swaps are needed, indicating the array is fully sorted. The algorithm has a time complexity of O(n^2) as each pass through the array requires n comparisons and there are n total passes needed in the worst case.

Uploaded by

blackcoder41
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Bubble Sort

Pseudocode and Flowchart


start
BubbleSort( int a[], int n)
Begin
for i = 1 to n-1 i
sorted = true n-1
1
for j = 0 to n-1-i
if a[j] > a[j+1] 1
temp = a[j]
a[j] = a[j+1]
a[j+1] = temp sorted = true
sorted = false
end for
if sorted j
break from i loop
0 n-1-i
end for
End 1

a[j] > a[j+1]


F
T

temp = a[j]
a[j] = a[j+1]
a[j+1] = temp

sorted = false

sorted == true
T
F
i

End
Bubble Sort

Bubble Sort Example

i =1 j 0 1 2 3 4 5 6 7
0 5 3 1 9 8 2 4 7
1 3 5 1 9 8 2 4 7
2 3 1 5 9 8 2 4 7
3 3 1 5 9 8 2 4 7
4 3 1 5 8 9 2 4 7
5 3 1 5 8 2 9 4 7
6 3 1 5 8 2 4 9 7
i=2 0 3 1 5 8 2 4 7 9
1 1 3 5 8 2 4 7
2 1 3 5 8 2 4 7
3 1 3 5 8 2 4 7
4 1 3 5 2 8 4 7
5 1 3 5 2 4 8 7
i=3 0 1 3 5 2 4 7 8
1 1 3 5 2 4 7
2 1 3 5 2 4 7
3 1 3 2 5 4 7
4 1 3 2 4 5 7
i=4 0 1 3 2 4 5 7
1 1 3 2 4 5
2 1 2 3 4 5
3 1 2 3 4 5
i=5 0 1 2 3 4 5
1 1 2 3 4
2 1 2 3 4
i=6 0 1 2 3 4
1 1 2 3
i=7 0 1 2 3
1 2

Note for array of size 8, outside i loop repeats 7 times.

Complexity
Clearly for an array of size n, the outside loop repeats n-1 times.

To begin with the inside loop does n-1 comparisons, next time n-2 and so on. Finally
on the last iteration of the outside loop, the inside loop does 1 comparison. So on
average the inside loop does ((n-1) + 1) / 2 ≈ n/2 comparisons.

Therefore, the overall number of computation steps is n * n/2 = n2/2

Complexity of bubble sort = O(n2)

You might also like