Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted.
Here's an example implementation of bubble sort in Java:
public class BubbleSortExample { public static void bubbleSort(int[] arr) { int n = arr.length; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { // Swap arr[j] and arr[j+1] int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } public static void main(String[] args) { int[] arr = { 64, 34, 25, 12, 22, 11, 90 }; bubbleSort(arr); System.out.println("Sorted array:"); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } }
This program defines a class BubbleSortExample with a bubbleSort method that takes an integer array arr, and sorts it using the bubble sort algorithm. The main method creates an example array arr, calls the bubbleSort method with this array, and then prints the sorted array.
The bubbleSort method works by first setting the size of the array n, and then looping over the array n-1 times. On each iteration, it loops over the remaining unsorted elements of the array and compares adjacent elements. If the elements are in the wrong order, they are swapped. The inner loop ends when it reaches the last unsorted element. The outer loop continues until all elements are sorted.
In the example above, the input array is { 64, 34, 25, 12, 22, 11, 90 }. After the first iteration of the outer loop, the array becomes { 34, 25, 12, 22, 11, 64, 90 }. After the second iteration, it becomes { 25, 12, 22, 11, 34, 64, 90 }, and so on, until the array is completely sorted.