algo: 冒泡排序(Java实现)

package com.liuxian.algo;

public class MySortClass implements Comparable<MySortClass> {
    public String userName;
    public int num;

    public MySortClass(String userName, int num) {
        this.userName = userName;
        this.num = num;
    }
    
    public int compareTo(MySortClass o) {
        return this.num - o.num;
    }
}
package com.liuxian.algo;

public class Helper {
    public static void printArray(MySortClass [] sorts) {
        for (int i = 0; i < sorts.length; i++) {
            System.out.println(sorts[i].num);
        }
    }
}
package com.liuxian.algo;

import java.util.Random;

public class BubbleSort {
    
    public static <AnyType extends Comparable<? super AnyType>> AnyType[]
        bubbleSort(AnyType[] a) {
        AnyType tmp;
        
        for (int i = 0; i < a.length; i++) {
            for (int j = i; j > 0; j--) {
                if((a[j].compareTo(a[j-1]) < 0)) {
                    tmp = a[j];
                    a[j] = a[j-1];
                    a[j-1] = tmp;
                }
            }
        }
        
        return a;
    }
        
    
    public static void main(String[] args) {
        int max = 100;
        Random random = new Random(100);
        MySortClass[] sort = new MySortClass[10];
        for (int i = 0; i < sort.length; i++) {
            int num = random.nextInt(max);
            sort[i] = new MySortClass(String.valueOf(num), num);
        }
        
        Helper.printArray(sort);
        System.out.println("after sort : ");
        sort = bubbleSort(sort);
        Helper.printArray(sort);
    }
}

output:

15
50
74
88
91
66
36
88
23
13
after sort : 
13
15
23
36
50
66
74
88
88
91

 

posted @ 2014-02-18 14:53  Kevin Liu Blog  阅读(242)  评论(0编辑  收藏  举报