How to implement Bubble Sort in Java

# How to implement Bubble Sort in Java

### Bubble Sort

Bubble sort also termed as sinking sort, is simple sorting algorithm which sort the list of data in ascending order by repeatedly stepping into it. In this algorithm, two adjacent element from list is compared and swapped if preceding element is greater than its next element. This will proceed throughout the list until all the elements are arranged into ascending order.

Bubble sort makes multiple passes to get the final result. Below figure shows the first pass-
The number of pairs from ‘N’ number of elements that will be required to compare in first pass is (N-1). Let us see a graphical representation how it is done in first pass- In the example we’ve five numbers of elements and number of pairs that will be required in first pass is (N-1) i.e. 4. This will go on until we’ve got a sorted series.

Let us see how this can be implemented in Java.

```package com.code2succeed.bubblesort;

public class BubbleSort {

public static void main(String[] args) {

//Create an array with data which is required to be sorted
int array[] = new int[]{3,-5,2,6,1};

//print array before sorting using bubble sort algorithm
System.out.println("Array Before Bubble Sort");
for(int i=0; i < array.length; i++){
System.out.print(array[i] + ",");
}

//Sorting the unsorted data using bubble sort algorithm
bubbleSort(array);

//Array output after sorting the data
System.out.println("Array After Bubble Sort");
for(int i=0; i < array.length; i++){
System.out.print(array[i] + " ");
}

}

private static void bubbleSort(int[] array) {

int l = array.length;
int temp = 0;

for(int i=0; i < l; i++){
for(int j=1; j < (l-i); j++){
if(array[j-1] > array[j]){
temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
}
}
}
}
}

```

#### Output:

```Array Before Bubble Sort
3 -5 2 6 1
Array After Bubble Sort
-5 1 2 3 6```

The number of passes required to complete the sorting is explained below: