众所周知,冒泡排序法在一般数组中就3步,
1 if(a<b){ 2 temp=a; 3 a=b; 4 b=temp; 5 }
然而,在集合中就不是简单的交换一下了,因为交换之后,必须保证新的值被重新设置到集合中去。那么变难了吗?实际上更简单了:
1 if(a<b){ 2 workerlist.get(j).setSc(b); 3 workerlist.get(j+1).setSc(a); 4 }
原理还是交换,不过不需要媒介temple 了。
具体代码见下:
*********************工人类**********************
package com.xtkj.worker;
public class Worker{
int id;
String name;
int age;
double salary;
public Worker(){} //构造方法
public Worker(int id,String name, int age,double salary ) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getSc() {
return salary;
}
public void setSc(double salary) {
this.salary = salary;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Worker getNext(){
return this.getNext();
}
}
*******************方法类(这里只讲解冒泡排序)***************
package com.xtkj.worker;
import Java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Method {
public static List<Worker> workerlist = new ArrayList<Worker>();
//按薪水由高到低排序
double temp;
double a=0;
double b=0;
void sort(){
System.out.println("按员工薪水从高到低排序结果为:");
for(int i=0;i<workerlist.size()-1;i++){
for(int j=0;j<workerlist.size()-1-i;j++){
a=workerlist.get(j).getSc();
b=workerlist.get(j+1).getSc();
if(a<b){
// temp=a;
workerlist.get(j).setSc(b); //注意:这里是把值设置到集合中去
// a=b;
workerlist.get(j+1).setSc(a); //简单的 a与b 交换,改变的只是从集合中取出来的结果,集合里面的元素并没有改变
// b=temp;
}
}
}
}
*****************界面类(测试类)**********************
package com.xtkj.worker;
import java.util.Scanner;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
Method method = new Method();
boolean b = true;
while(b){
System.out.println();
System.out.println("*********************欢迎进入职员薪水管理系统***********************");
System.out.println("请选择以下操作:");
System.out.println("1.添加新员工");
System.out.println("2.查询员工信息");
System.out.println("3.显示所有员工信息");
System.out.println("4.修改员工薪水");
System.out.println("5.删除员工信息");
System.out.println("6.薪水由低到高排列");
System.out.println("7.统计员工平均工资和最低、最高工资");
System.out.println("8.退出本系统");
Scanner reader=new Scanner(System.in );
System.out.println("请输入功能:");
int ab = reader.nextInt();
switch(ab)
{
case 1:
method.add();
break;
case 2:
method.find();
break;
case 3:
method.showAll();
break;
case 4:
method.updatesal();
break;
case 5:
method.delete();
case 6:
method.sort();
break;
case 7:
method.statics();
break;
case 8:
System.out.println("已退出职员薪水管理系统!");
b = false;
}
}
Worker wr=new Worker();
}
}
运行结果如下: