Here is the Java code for bubble sort:

public class BubbleSort {
    public static void main(String[] args) {
        int[] arr = {5, 2, 8, 3, 9, 1};
        int temp;
        boolean swapped;
        
        for (int i = 0; i < arr.length - 1; i++) {
            swapped = false;
            for (int j = 0; j < arr.length - i - 1; j++) {
                if (arr[j] > arr[j+1]) {
                    temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                    swapped = true;
                }
            }
            if (!swapped) {
                // if no swaps occur, array is already sorted
                break;
            }
        }
        
        // print the sorted array
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}

In this program, we use two loops to iterate over the array and compare adjacent elements. If the element on the left is greater than the element on the right, we swap them. This process is repeated until the array is sorted. The swapped variable is used to check if any swaps have been made in a particular iteration. If no swaps occur, the array is already sorted and we can exit the loop early. Finally, we print the sorted array.

write-a-program-to-realize-bubble-sort-by-java

原文地址: https://www.cveoy.top/t/topic/mZO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录