Home >>Java Programs >Java Program for bubble sort
In this example, we will create a java program to sort array elements using bubble sort algorithm.
This Bubble sort algorithm is known as the simplest sorting algorithm. In this algorithm, the array is traversed from first element to the last element. The current element is compared with the next element and if current element is greater than the next element then it is swapped.
Program:
public class Main {
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,55,21,5,32,15,7,1,49,83};
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] + " ");
}
}
}