Home > Java > javaTutorial > java bubble sort algorithm code

java bubble sort algorithm code

高洛峰
Release: 2017-01-17 12:52:50
Original
1858 people have browsed it

/**
 * 原理:
 * 进行n次循环,每次循环从后往前对相邻两个元素进行比较,小的往前,大的往后
 * 
 * 时间复杂度:
 * 平均情况:O(n^2)
 * 最好情况:O(n)
 * 最坏情况:O(n^2)
 *
 * 稳定性:稳定
 **/
public class 冒泡排序 {
    public int[] bubbleSort(int[] a, int n) {
        for (int i = 0; i < n; i++) {
            int flag = 0;
            for (int j = n - 1; j > i; j--) {// i or i-1 ?
                if (a[j] < a[j - 1]) {
                    int x = a[j];
                    a[j] = a[j - 1];
                    a[j - 1] = x;
                    flag = 1;
                }
            }
            if (flag == 0)
                break;
        }
        return a;
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] a = new int[] { 25, 56, 32, 20, 1, 5, 89, 3, 8, 41 };
        冒泡排序 sort = new 冒泡排序();
        sort.bubbleSort(a, a.length);
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i] + " ");
        }
    }
}
Copy after login


For more articles related to java bubble sort algorithm code, please pay attention to the PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template