排序算法(三) 冒泡排序

来源:岁月联盟 编辑:exp 时间:2012-09-15

冒泡排序

依次遍历数组

每次从头遍历数组将最大的值移动到最右端

 

代码实现

[html] 
package com.robert.paixu; 
 
/** 
 * 冒泡排序 
 * 从小到大 
 * @author Administrator 
 */ 
public class BubbleSortAlgorithm { 
     
    public static void main(String[] args) 
    { 
        int[] arrays = {1,9,2,8,3,7,4,5,0,10,18,11}; 
        bubbleSort(arrays); 
        display(arrays); 
    } 
     
    /** 
     * 冒泡排序 
     * @param arrays 
     */ 
    private static void bubbleSort(int[] arrays) 
    { 
        int temp = 0; 
        for(int i=0;i<arrays.length-1;i++) 
        { 
            for(int j=0;j<arrays.length-i-1;j++) 
            { 
                if(arrays[j]>arrays[j+1]) 
                { 
                    temp = arrays[j]; 
                    arrays[j] = arrays[j+1]; 
                    arrays[j+1] = temp; 
                } 
            } 
        } 
    } 
     
    /** 
     * 显示数组的值 
     * @param arrays 
     */ 
    private static void display(int[] arrays) 
    { 
        for(int i=0;i<arrays.length;i++) 
        { 
            System.out.print(arrays[i]+" "); 
        } 
    } 

该算法的时间复杂度为:

在任何情况下,都为O(n^2)
 

图片内容