Bubble sort and optimization

Bubbling sorting idea: for a group of two comparisons, let the larger number go backwards, perform multiple times (the number of times is determined by the specific array), and then the array will be sorted from small to large;

//Optimize the source code before

package com.company;
import java.util.Arrays;
public class Main {

public static void sequence(int[] arr){          //对数组所有数进行排序;

    for (int k=0;k<arr.length-1;k++){

         for(int j = 1; j <arr.length-k; ++j) {
            if (arr[j-1]>arr[j]){
                swap(arr,j-1,j);

            }
        }

         
    }
}
    public static void printArray(int[] array) {      //遍历输出
        for (int e : array) {
            System.out.print(e + " ");
        }
    }

    public static void swap(int[] arr,int a,int b){    //交换前后数值
        int temp=arr[a];
        arr[a]=arr[b];
        arr[b]=temp;

    }
    public static void main(String[] args) {
        int[] arr={1,3,5,2};
        sequence(arr);
        printArray(arr);

    }
}

//Optimization can use the boolean type for detection. If there is no exchange during a comparison, the order has been arranged.

//Source code after optimization

package com.company;
import java.util.Arrays;
public class Main {

public static void sequence(int[] arr){          //对数组所有数进行排序;

    for (int k=0;k<arr.length-1;k++){
      boolean isChange=false;
         for(int j = 1; j <arr.length-k; ++j) {
            if (arr[j-1]>arr[j]){
                swap(arr,j-1,j);
                isChange=true;
            }
        }
        if(isChange==false) {    //检测经过一次内循环后isChange是否改变,如果没改变则没有进行交换,直接返回;
            return;
        }
    }
}
    public static void printArray(int[] array) {      //遍历输出
        for (int e : array) {
            System.out.print(e + " ");
        }
    }

    public static void swap(int[] arr,int a,int b){    //交换前后数值
        int temp=arr[a];
        arr[a]=arr[b];
        arr[b]=temp;

    }
    public static void main(String[] args) {
        int[] arr={1,3,5,2};
        sequence(arr);
        printArray(arr);

    }
}

Guess you like

Origin blog.csdn.net/tdongmu/article/details/108919841