Bubble Sort in Java

Bubble Sort in Java

We can create a java program to sort array elements using bubble sort.

Bubble sort algorithm is known as the simplest sorting algorithm.

In this algorithm, array is traversed from first element to last element. Here, current element is compared with the next element. If current element is greater than the next element, it is swapped.

What is Bubble Sort in Java?

This sorting algorithm is the simplest sorting algorithm, here the array is traversed from beginning to end. In other words, we compare adjacent elements. The first element is compared with the second one then the second is compared with the third one and so on. If the current element is greater than the next element then it is swapped.

Java Bubble Sort Example

To sort an array of elements (7, 3 , 1 , 2 , 5), we are using Bubble Sort in Java.

First Pass:

7 3 1 2 5 ( The first two elements are compared and if the first is greater than second then we will swap)

=> 3 7 1 2 5 (no change because the first element is less than the second element)

3 7 1 2 5

=> 3 1 7 2 5 (swap because 7 is greater than 1)

3 1 7 2 5

=> 3 1 2 7 5 (swap because 7 is greater than 2)

3 1 2 7 5 (swap because 7 is greater than 5)

=> 3 1 2 5 7

Now the first pass is complete we will move towards the second pass

Second Pass:

3 1 2 5 7

=> 1 3 2 5 7 (swap because 3 is greater than 1 )

1 3 2 5 7

=> 1 2 3 5 7 (swap because 3 is greater than 2)

1 2 3 5 7 (no change)

1 2 3 5 7 (no change)

1 2 3 5 7

public class BubbleSortUsingJava {
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;
}

}
}

}
public static void main(String[] args) {
int arr[] ={3,60,35,2,45,320,5};

System.out.println("Array Before Bubble Sort");
for(int i=0; i < arr.length; i++){
System.out.print(arr[i] + " ");
}
System.out.println();

bubbleSort(arr);//sorting array elements using bubble sort

System.out.println("Array After Bubble Sort");
for(int i=0; i < arr.length; i++){
System.out.print(arr[i] + " ");
}

}
}

Output
Array Before Bubble Sort
3 60 35 2 45 320 5
Array After Bubble Sort
2 3 5 35 45 60 320

 

%d bloggers like this: