Java 冒泡排序代码

public class BubbleSort { public static void bubbleSort(int[] arr) { int n = arr.length; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { // 交换arr[j]和arr[j+1] int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } }

text
复制代码
public static void main(String[] args) { int[] arr = {5, 1, 4, 2, 8}; bubbleSort(arr); System.out.println(Arrays.toString(arr)); }

}

0个评论
点击登录,快来和大家讨论吧~
表情
图片
暂无评论
下载 APP