0% found this document useful (0 votes)
23 views

BubbleSort_Example

The document explains the bubble sort algorithm using an example array. It details each step of the sorting process, showing how elements are compared and swapped to sort the array in ascending order. By the end of the fourth pass, the array is fully sorted with the largest elements moved to their correct positions.

Uploaded by

Md.Fahim
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

BubbleSort_Example

The document explains the bubble sort algorithm using an example array. It details each step of the sorting process, showing how elements are compared and swapped to sort the array in ascending order. By the end of the fourth pass, the array is fully sorted with the largest elements moved to their correct positions.

Uploaded by

Md.Fahim
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Example: Let’s consider an array: int a[5] = {4, 6, 2, 9, 1}

Below, we have a pictorial representation of how bubble sort will sort the given array.
Step/pass 1: when i = 0
a[0] a[1] a[2] a[3] a[4]
j=0 4 6 2 9 1 4 > 6 (False), No Swapping

j=1 4 6 2 9 1 6 > 2 (True), Swapping happens

j=2 4 2 6 9 1 6 > 9 (False), No Swapping

j=3 4 2 6 9 1 9 > 1 (True), Swapping happens

4 2 6 1 9 The largest element (9) bubbled up

Step/pass 2: when i = 1
a[0] a[1] a[2] a[3] a[4]
j=0 4 2 6 1 9 4 > 2 (True), Swapping happens

j=1 2 4 6 1 9 4 > 6 (False), No Swapping

j=2 2 4 6 1 9 6 > 1 (True), Swapping happens

2 4 1 6 9 The 2nd largest element (6) bubbled up

Step/pass 3: when i = 2
a[0] a[1] a[2] a[3] a[4]
j=0 2 4 1 6 9 2 > 4 (False), No Swapping

j=1 2 4 1 6 9 4 > 1 (True), Swapping happens

2 1 4 6 9 The 3rd largest element (4) bubbled up

Step/pass 4: when i = 3
a[0] a[1] a[2] a[3] a[4]
j=0 2 1 4 6 9 2 > 1 (True), Swapping happens

1 2 4 6 9 The 4th largest element (2) bubbled up;


array is sorted

So, as we can see in the representation above, after the first step/pass, 9 is placed at the last
index, which is the correct position for it.
Similarly, after the second step/pass, 6 is placed at the second last index, and so on.

2 Bulbul Ahamed, Associate Professor, NUB www.bulbulcse.com

You might also like