Home » Java » Bubble Sort Algorithm with full code – Java

Bubble Sort Algorithm with full code – Java

In this tutorial, we are going to learn how to implement bubble sort in java. Bubble sort is a very popular and very useful algorithm in programming.

Here, I will create a class “Sotrs” and a method “bubbleSort”. The method declared as a static method because we can call static methods directly without creating an instance of the corresponding class.

Also, there is an integer array called “arr1” with 5,3,8,4,6 elements. There are two for loop in the main method. The for loop number one will print the elements of the array before the sorting and the for loop number two will print the elements in the array two after the sorting.

In line 1, the bubbleSort method will be called with a parameter. Here the parameter is out the array.

Now we look at steps in the bubbleSort method. Following figure explain the basic steps in bubble sort algorithm.

Here I will declare two variables called n and temp. n will be assigned length of the array and temp will be assigned zero. Out for loop runs n times. In the inner for loop, if the value of the left-hand side element is greater than the value of the right-hand side element, the values of each element will be swapped with the help of temp variable.

public class Sorts {

public static void main(String[] args) {
int[] arr1 = {5,3,8,4,6};
System.out.println("Before Bubble Sort");

// For loop number two
for(int i: arr1){
System.out.print(i + " ");
}
System.out.println();

// sorting array using  bubble sort
bubbleSort(arr1); // line 1
// For loop number one
System.out.println("After bubble Sort");
for(int i: arr1){
System.out.print(i+" ");
}
}

static void bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(arr[j-1] > arr[j]){
//swap elements
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}
}

Top Posts & Pages

The Big DayJune 28, 2019
The big day is here.