# DSA — Bubble Sort Algorithm

In my previous article, I had published about the Binary Search Algorithm. The main problem and hurdle in Binary Search Algorithm was it required a sorted list.

# What is a sorted and unsorted List/Array ?

Sorted Array/List is an array Data Structure or List Data Structure which stores the elements in either Numerical, Alphabetical or some other order and placed at equally spaced addresses in computer memory addresses.

Unsorted Array/List like the name suggests is not sorted and does not store the elements in any order.

# What is a Bubble Sort Algorithm?

Bubble Sort Algorithm is an algorithm that is used to sort an unsorted List/Array. Bubble sort is probably the fastest sort available under very specific circumstances. It originally became well known primarily because it was one of the first algorithms that was rigorously analyzed and proof was found that it was optimal under its limited circumstances. It uses multiple iterations to give us the output.

# Why use the Bubble Sort Algorithm?

Bubble Sort Algorithm is used when we have an Unsorted List/Array and we need to sort it and use it for some other functionalities. Since it is a basic algorithm it can be only used to sort tiny sets. For large sets of data this algorithm will not be optimal.

# Steps for Bubble Sort Algorithm

Consider we have an unsorted Array/List arr=[8,5,3,1,4,7,9]. As you can see it is an unsorted List and the numbers are placed randomly. The main purpose of our algorithm would be to sort this array and the result we would expect is arr=[1,3,4,5,7,8,9]. The steps that we would follow are:

1. First Iteration (Compare and Swap)

1.1. Starting from the first index, Compare the first and the second elements. In our array, the first element is 8 and the second is 5.

1.2. If the first element is greater than the second element, they are swapped. Since in our array the first element is greater than the second element we will swap it (8 > 5).

1.3. Now, compare the second and the third elements. Swap them if they are not in order. After the previous step, the second element is 8 and the third element is 3. As 8 > 3 we would swap the second and third element.

1.4. The above process goes on until the last element.

2. Remaining Iterations

• The same process goes on for the remaining iterations.
• After each iteration, the largest element among the unsorted elements is placed at the end.
• The array is sorted when all the unsorted elements are placed at their correct positions.

The visual representation of our example would be: