眾所周知,冒泡排序法在一般數組中就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();
}
}
運行結果如下: