冒泡排序

话不多说,直接上代码(Coding):

/**
 * 冒泡排序 冒泡排序作为一种算法 是用来实现快速排序的
 */
public class Demo02 {
    public static void main(String[] args) {
        // 1、定义一组元素列表(有负数的情况)
        int[] numList = new int[]{1, 23, 67, 56, 24, -1, 0};
        // 3、进行冒泡排序 这里数组也是对象 因此 这个参数传递 传递的不是值 而是数组对象在栈内存的地址
        bubbleAsc(numList); // 升序
        bubbleDesc(numList); // 降序
        // 4、进行打印输出
        for (int i = 0; i < numList.length; i++) {
            System.out.print(i == numList.length - 1 ? numList[i] : numList[i] + ",");
        }
    }

    /**
     * 冒泡排序 升序
     *
     * @param numList
     */
    private static void bubbleAsc(int[] numList) {
        // Arrays.sort(numList);
        for (int i = 0; i < numList.length - 1; i++) {
            for (int j = 0; j < numList.length - i - 1; j++) {
                // 4 3 2 1
                if (numList[j] > numList[j + 1]) {
                    // 替换
                    int temp = numList[j + 1];
                    numList[j + 1] = numList[j];
                    numList[j] = temp;
                }
            }
        }
    }

    /**
     * 冒泡排序 降序
     *
     * @param numList
     */
    private static void bubbleDesc(int[] numList) {
        // Arrays.sort(numList);
        for (int i = 0; i < numList.length - 1; i++) {
            for (int j = 0; j < numList.length - i - 1; j++) {
                // 1 2 3 4
                if (numList[j] < numList[j + 1]) {
                    // 替换
                    int temp = numList[j];
                    numList[j] = numList[j + 1];
                    numList[j + 1] = temp;
                }
            }
        }
    }
}

  

posted @ 2023-01-29 16:07  AxeBurner  阅读(13)  评论(0编辑  收藏  举报