/**
* 冒泡排序法
* @author Sailing
*
*/
public class BubbleSort {
/**
* 可以看到,对于n个数,冒泡排序法完成所有的排序需要 n*(n-1)/2,它的时间复杂度为 O(n*(n-1)/2)
* 如果n过于大,那么此时 0.5可以忽略掉,即冒泡排序法的时间复杂度为 O(N^2)
* @param args
* @author Sailing
*/
public static void main(String[] args) {
List<MyUser> userList = new BubbleSort().getParam();
new BubbleSort().sortName(userList);
}
/**
* 简单的冒泡排序
*
* @author Sailing
*/
public void simple(){
int [] arrayTest = {14,10,26,86,65,75,41,22,64,55,99};//11
int length = arrayTest.length;
System.out.println(length);
int t = 0;
for(int i : arrayTest){
System.out.print(i + " ");
}
for(int i=0;i<length-1;i++){
for(int j=0;j<length-i-1;j++){
if(arrayTest[j]<arrayTest[j+1]){
t = arrayTest[j];
arrayTest[j] = arrayTest[j+1];
arrayTest[j+1] = t;
}
}
}
System.out.println();
for(int i : arrayTest){
System.out.print(i + " ");
}
}
/**
* 按照分数的高低,对modelList进行冒泡排序,
* @param userList
* @author Sailing
*/
public void sortName(List<MyUser> userList){
System.out.println(userList.toString());
int userSize = userList.size();
MyUser model;
for(int i = 0;i<userSize-1;i++){
for(int j=0;j<userSize-1-i;j++){
if(userList.get(j).score<userList.get(j+1).score){
model = userList.get(j);
userList.set(j, userList.get(j+1));
userList.set(j+1,model);
}
}
}
System.out.println(userList.toString());
}
/**
* 获取要排序的集合
* @return
* @author Sailing
*/
public List<MyUser> getParam(){
List<MyUser> list = new ArrayList<>();
for(int i=0;i<10;i++){
MyUser model = new MyUser();
model.id = i;
//(数据类型)(最小值+Math.random()*(最大值-最小值+1)) 65 90
int name_f = (int)(65 + Math.random()*26);
int name_l = (int)(65 + Math.random()*26);
double score = Math.random()*100;
char cf = (char) name_f;
char cl = (char) name_l;
String name = (""+cf+cl);
model.name = name;
model.score = score;
System.out.println(name+" "+score);
System.out.println("====================");
list.add(model);
}
return list;
}
class MyUser{
public Integer id;
public String name;//名字
public Double score;//分数
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", score=" + score + "]";
}
}
}