# Algorithm: Bubble Sort
###### tags: `Algorithm`
[TOC]
## What is Bubble Sort?

1. An unsorted array is traversed from first element to last element.
2. Current element is compared with the next element.
3. If current element is bigger than next one, then swap function is called.
## How to implement BubbleSort?
You will have to itinerate all items. As you have to compare current item with the next one, you will have nested loop.
Notice that the 2nd loop only goes until **j<(n-i)**, that is because we do not itinerate over those items that are already in place.
>**++Example:++**
First loop round, we will send the biggest number to the last position in array, then there is no meaning to compare it again, right? [color=pink]
```java==
//Bubble Sort
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(arr[j-1] > arr[j]){
//swap elements
swap(arr, j-1, j);
}
}
}
private static void swap(int[]array, int i, int d){
int tmp = array[i];
array[i] = array[d];
array[d] = tmp;
}
```
## Advantages & Disadvantages
>**Advantage:** [color=lightgreen]
>1. Easy to understand and apply.
>2. Not the quickest sort.
>**Disadvantage:** [color=red]
The time taken by Bubble Sort, will increase exponentially as the amount of items in the array increases.
Example: If items get x10 bigger, then time takes x100 longer.