交换排序之冒泡排序(java实现)

import java.util.Arrays;


public class BubbleSort {

    public static void bubbleSort(DataWraper[] data){
        System.out.println("开始排序");
        int arrayLength=data.length;
        for(int i=0;i<arrayLength-1;i++){
            boolean flag=false;
            for(int j=0;j<arrayLength-i-1;j++){
                if(data[j].compareTo(data[j+1])>0){
                    DataWraper tmp=data[j+1];
                    data[j+1]=data[j];
                    data[j]=tmp;
                    flag=true;
                }
            }
            System.out.println(Arrays.toString(data));
            //如果该趟没有发生交换,则表明已处于有序状态
            if(!flag){
                break;
            }
        }
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        DataWraper [] data={
                new DataWraper(21, ""),
                new DataWraper(30, ""),
                new DataWraper(49, ""),
                new DataWraper(30, "*"),
                new DataWraper(16, ""),
                new DataWraper(9, ""),
               
        };
        System.out.println("排序之前:\n"+Arrays.toString(data));
        bubbleSort(data);
        System.out.println("排序之后:\n"+Arrays.toString(data));
    }

}

结果:

排序之前:
[21, 30, 49, 30*, 16, 9]
开始排序
[21, 30, 30*, 16, 9, 49]
[21, 30, 16, 9, 30*, 49]
[21, 16, 9, 30, 30*, 49]
[16, 9, 21, 30, 30*, 49]
[9, 16, 21, 30, 30*, 49]
排序之后:
[9, 16, 21, 30, 30*, 49]

posted @ 2011-07-18 13:41  朱旭东  阅读(429)  评论(0编辑  收藏  举报