Bubble sort is one of the sorting algorithm used to sort data structures like an array, linked list etc. The basic idea of the bubble sort is to compare the two adjacent values in the array and swap them accordingly. By repeating this step in the loop we finally get array sorted.

## Steps to Sort an Array using Bubble Sort

1. Initialize an array with the values.
2. Using loops compare two adjacent elements in the array
3. If array[j] > array[j+1] then swap both of them. Repeat this step with the next two adjacent elements. By doing this largest element will be shifted to the last of the array.
4. Now again compare two adjacent elements in the array from start till 2nd last element .and swap them if required. And by doing this you will successfully able to shift 2nd largest element in the array to 2nd last position.
5. Repeat the above steps with each time decreasing the loop counter 1 from the last. (This will ensure the largest element in the unsorted partition will shift to rightmost end).
6. Stop if the unsorted partition is only left to one.
7. The array is successfully sorted.

## Java

The most important step in the bubble sort is the swapping of the two elements. The code in the program used for swapping element is:

Here we are copying the 1st variable’s value into a temporary variable, then overriding the 1st variable’s value with 2nd variable ‘s value. Then finally updating the 2nd variable value with the temporary value (copy of the 1st variable’s value).

Note: In swapping if we would not have stored 1st variable’s value into a temporary location then we could have lost that value on updating it with the 2nd variable’s value.

Output of Program ## Bubble Sort Overview

• In place Algorithm – We don’t require an extra array to sort an array.
• O(n²) time complexity – quadratic.
• Becomes insufficient as array sizes grow large.

That’s all we need to do in order to sort array values using bubble sort algorithm. If you face any difficulties then do comment below.