/**

  • 经典的冒泡排序算法

  • @author 屌丝程序员 */ public class BubbleSort { public static void main(String[] args) { int[] arr = { 5, 3, 8, 6, 4 }; bubbleSort(arr); System.out.println('排序后的数组:'); for (int i : arr) { System.out.print(i + ' '); } }

    /**

    • 冒泡排序函数
    • @param arr 待排序的数组 */ public static void 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] > arr[j + 1]) { swap(arr, j, j + 1); } } } }

    /**

    • 交换数组中指定位置的两个元素
    • @param arr 待交换的数组
    • @param i 第一个元素的下标
    • @param j 第二个元素的下标 */ public static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } }
屌丝程序员的冒泡排序:Java 代码实现

原文地址: https://www.cveoy.top/t/topic/mv2e 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录