algo: 冒泡排序(Java实现)

断了今生、忘了曾经 提交于 2019-12-20 00:44:07
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

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!