java算法之冒泡排序

来源:互联网 发布:小米note3卸载软件 编辑:程序博客网 时间:2024/05/22 06:42

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

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)—最坏

原创粉丝点击