java算法之冒泡排序

xiaoxiao2021-02-28  94

基本思想 拿数组元素跟下一个元素相比,如果下个元素大,则交换位置,每轮循环得出最大值(冒泡);如此循环,排序完成 代码

public class BubbleSort { public static void bubbleSort(int[] arr) { int temp; 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]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } public static void main(String[] args) { int[] a = new int[] { 49, 38, 65, 97, 76, 13, 27, 50 }; bubbleSort(a); for (int i : a) System.out.print(i + " "); } }

时间复杂度 O(n)——最好 O(n^2)—平均 O(n^2)—最坏

转载请注明原文地址: https://www.6miu.com/read-65993.html

最新回复(0)