時間複雜度n*k/2,對一串數中排列出前5和後5,前十個冒泡排序,後面的堆排序。降低了時間複雜度。
傳入二維字符串數組,一個還是name一個是要排列的數。
/**
* 建立而二維數組,排序前五個和後五個
* @param con 二維數組,名字和數據
* @return 前5個最小,後5個最大,大小爲10的數組
*/
public String [][] getFive(String[][] con) {
float[] save = new float[10];
String[] name = new String[10];
int sum = 10;
if (con.length < 10) {
sum = con.length;
}
for (int i = 0; i < sum; i++) {
try {
save[i] = Float.valueOf(con[i][1]);
name[i] = con[i][0];
} catch (Exception e) {
}
}
float temp = 0;
String strTemp = "";
for (int i = 0; i < save.length; i++) {
for (int j = 0; j < save.length; j++) {
if (save[i] < save[j]) {
strTemp = name[i];
name[i] = name[j];
name[j] = strTemp;
temp = save[i];
save[i] = save[j];
save[j] = temp;
}
}
}
if (con.length > 10) {
//存儲當前數
float test = 0;
for (int i = 10; i < con.length; i++) {
try {
test = Float.valueOf(con[i][1]);
if (test >= save[9]) {
for (int j = 5; j <=9; j++) {
if (j == 9) {
save[j] = test;
name[j]=con[i][0];
}else{
save[j] = save[j + 1];
name[j]=name[j+1];
}
}
continue;
}
if (test <= save[0]) {
for (int j = 4; j >= 0; j--) {
if (j == 0) {
save[j] = test;
name[j]=con[i][0];
}else{
save[j] = save[j - 1];
name[j]=name[j-1];
}
}
continue;
}
for (int p = 1; p < 5; p++) {
if (test >= save[p - 1] && test < save[p]) {
for (int j = 4; j >= p; j--) {
if (j == p) {
save[j] = test;
name[j]=con[i][0];
} else {
save[j] = save[j - 1];
name[j] = name[j-1];
}
}
break;
}
}
for (int p = 6; p < 10; p++) {
if (test > save[p-1] && test <= save[p]) {
for (int j = 5; j < p; j++) {
if (j == p-1) {
save[j] = test;
name[j] = con[i][0];
continue;
} else {
save[j] = save[j+1];
name[j] = name[j+1];
}
}
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
String [][] str=new String[2][10];
for(int i=0;i<10;i++){
str[0][i]=name[i];
str[1][i]=save[i]+"";
}
return str;
}