# What Is Bubble Sort in Data Structure?

//

Larry Thompson

Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. This algorithm is called Bubble Sort because with each iteration, the largest unsorted element “bubbles” up towards its correct position.

How does Bubble Sort work?
Bubble Sort works by comparing adjacent elements and swapping them if they are in the wrong order. This process continues until the entire list is sorted.

Here’s how Bubble Sort works step by step:

1. Compare the first element with the second element. If they are in the wrong order, swap them. 2. Move to the next pair of adjacent elements, and perform the same comparison and swap operation. 3.

Repeat steps 1 and 2 for every pair of adjacent elements until you reach the end of the list. 4. When you reach

### the end of the list

, start again from

### the beginning

. 5. Repeat this process until no more swaps are required, indicating that

## the list is now sorted

.

An example to understand Bubble Sort:
Let’s say we have an unsorted list: [5, 3, 8, 2].

1. In the first pass, we compare 5 and 3. Since they are in the wrong order, we swap them: [3, 5, 8, 2]. Next, we compare 5 and 8. They are already in order, so no swap is needed: [3, 5, 8, 2]. Then we compare 8 and 2. Again, they are in the wrong order, so we swap them: [3, 5, 2, 8].

At this point, we have completed

### the first pass

. The largest element (8) has “bubbled” up to the end of the list. Now we start the second pass and repeat steps 1-4. 6. After the second pass, the list becomes: [3, 2, 5, 8]. 7. We continue the third pass and compare each pair of adjacent elements. 8. Finally, after the fourth pass,

## the list is sorted

: [2, 3, 5, 8].

Time Complexity of Bubble Sort:
The worst-case time complexity of Bubble Sort is O(n^2), where n is the number of elements in the list. This means that as the number of elements increases, the time taken to sort them using Bubble Sort grows exponentially.

Conclusion:
Bubble Sort is a simple sorting algorithm that repeatedly compares and swaps adjacent elements until the entire list is sorted. While it is easy to understand and implement, Bubble Sort is not efficient for large lists due to its O(n^2) time complexity.

By using Bubble Sort as an example in this tutorial, you now have a better understanding of how sorting algorithms work and can apply this knowledge to solve other sorting problems efficiently.