Java advanced bubble sort

Bubble Sort

  • Idea: Compare adjacent elements in pairs, put the larger ones in the back. After the first time, the maximum value appears at the maximum index. If you continue with the same principle, you can get a sorted array. .
  • Example
    1. Original array
    Insert picture description here
    2. After the first sorting
    Insert picture description here
    3. After the second sorting
    Insert picture description here
    4. After the third sorting
    Insert picture description here
    5. After the fourth sorting
    Insert picture description here
  • law

1. Two-by-two comparison, put the bigger one later
2. After each comparison is completed, the next comparison will always reduce one element comparison
3. The first comparison, there are zero elements that are not
   compared, the second comparison, there is one element Not
   compared to the third time, there are two elements not compared
   ...

4. A total of -1 times need to compare array length

Code

public class Test {
    
    
    public static void main(String[] args) {
    
    
        int[] array=new int[]{
    
    24,69,80,57,13};
        System.out.println("排序前");
        printArray(array);
        bubbleSort(array);
        System.out.println("排序后");
        printArray(array);
    }
    
    public static int[] bubbleSort(int[] arr){
    
    
        for(int i=0;i<arr.length-1;i++){
    
    
            for(int j=0;j<arr.length-1-i;j++) {
    
    
                if (arr[j + 1] < arr[j]) {
    
    
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        return arr;
    }
    
    public static void printArray(int[] arr){
    
    
        System.out.print("[");
        for (int i=0;i<arr.length;i++){
    
    
            if(i==arr.length-1){
    
    
                System.out.print(arr[i]);
            }
            else{
    
    
                System.out.print(arr[i]+",");
            }
        }
        System.out.println("]");
    }
}

Insert picture description here
Java introductory basic learning (1)
Java introductory basic learning (2)
Java introductory basic learning (3)
Common objects of advanced java (1)

Guess you like

Origin blog.csdn.net/qq_45798550/article/details/107935684