public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 3, 1, 7, 9, 4, 6}; // array to be sorted
// bubble sort algorithm
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 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;
}
}
}
// print the sorted array
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
This program uses the bubble sort algorithm to sort the input array of integers. The algorithm works by repeatedly swapping adjacent elements if they are in the wrong order, until the array is sorted. The program uses two nested loops to compare adjacent elements and swap them if necessary. The sorted array is then printed to the console. In the example array above, the sorted array would be: 1 2 3 4 5 6 7 8 9.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
This program uses the bubble sort algorithm to sort the input array of integers. The algorithm works by repeatedly swapping adjacent elements if they are in the wrong order, until the array is sorted. The program uses two nested loops to compare adjacent elements and swap them if necessary. The sorted array is then printed to the console. In the example array above, the sorted array would be: 1 2 3 4 5 6 7 8 9.