Home  >  Article  >  Java  >  Java implements simple bubble sort code

Java implements simple bubble sort code

WBOY
WBOYOriginal
2024-01-30 09:34:051333browse

Java implements simple bubble sort code

The simplest code example of Java bubble sort

Bubble sort is a common sorting algorithm. Its basic idea is to compare and sum adjacent elements. Exchange to gradually adjust the sequence to be sorted into an ordered sequence. The following is a simple Java code example that demonstrates how to implement bubble sort:

public class BubbleSort {
    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]) {
                    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("排序后的数组:");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}

In this example, we define a BubbleSort class, which contains a static method named bubbleSort. This method accepts an array of type int as a parameter and sorts the array using the bubble sort algorithm.

The core part of the algorithm is two nested for loops. The outer loop controls the number of rounds of comparison, and a total of n-1 rounds of comparison are required (n is the array length). The inner loop controls each round of compare and swap operations. We determine whether they need to swap positions by comparing the sizes of two adjacent elements. If the previous element is larger than the next element, swap their positions.

In the main method, we create an array arr to be sorted and call the bubbleSort method for sorting. Finally, we output the sorted array by looping over it.

The above is the simplest code example to implement bubble sort using Java. Although bubble sort is simple, it is less efficient for sorting larger-scale data, so more efficient sorting algorithms are often used in practical applications. But as an entry-level sorting algorithm, it still has important value in teaching and understanding.

The above is the detailed content of Java implements simple bubble sort code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn