java数组排序,冒泡法

冒泡排序法:顾名思义,从下到上,两两进行比较,越小的越往上,从而形成由小到大的排序。

public static void bubble(int[] arr){
        
        int temp;
        //根据角标进行比较,
        for(int i = 0; i<arr.length; i++){
            //j是数组的最后一个角标
            for (int j = arr.length-1; j > i; j--) {
                
                if (arr[j] < arr[j - 1]) {
                    //从后往前进行比较,小数往前,一轮之后最小数就在最前面了
                    temp = arr[j - 1];
                    arr[j - 1] = arr[j];
                    arr[j] = temp;
                }
            }
        }
    }
    
    public static void main(String[] args) {
    
        int[] arr = {3,22,5,3,66,2,9};
        
        bubble(arr);
        
        //使用foreach循环输出
        for(int x : arr){
            System.out.println(x);
        }
        //使用字符串表达形式输出,输出形式更为直观        
        System.out.println(Arrays.toString(arr));
    }

 以下是看教程的类似的方法

package ch05;

/**
 *
 * @classname: paixu
 * @time: 2020年4月30日
 * @author: 嘉年华
 */
public class paixu {

    public static void main(String[] args) {
        int[] a = { 25, 24, 12, 76, 98, 101, 90, 28 };
        for (int i = 0; i < a.length-1 ; i++) {
            for (int j = i; j < a.length; j++) {
                if (a[i] > a[j]) {
                    int temp = a[j];
                    a[j] = a[i];
                    a[i] = temp;
                }
            }
        }
        for (int i:a) {
            System.out.print(i+" ");
        }

    }

}
原文地址:https://www.cnblogs.com/faberbeta/p/12807903.html