设计一个通用的排序算法,作为验证,自定义学生累 矩形类
可以利用该排序算法对学生按照ID据NAME进行排序;对矩形按面积进行排序
说明:一个通用的排序程序只要知道数组中任意2个元素如何比较大小究竟可以完成排序
java:设计一个通用的排序算法.
答案:2 悬赏:10 手机版
解决时间 2021-04-12 18:00
- 提问者网友:椧運幽默
- 2021-04-11 22:49
最佳答案
- 五星知识达人网友:持酒劝斜阳
- 2021-04-11 23:53
import java.util.Arrays;
class Stu implements Comparable{
String name;
int id;
public Stu (String n, int i){
name = n;
id = i;
}
public int compareTo(Object o){
Stu m = (Stu) o;
if (id > m.id){
return 1;
} else if(id < m.id){
return -1;
} else return 0;
}
public String toString(){
return "("+name+","+id+")";
}
}
class Rec implements Comparable{
int c, k;
public Rec (int m, int n){
c = m;
k = n;
}
int area (){
return c*k;
}
public int compareTo(Object o){
Rec m = (Rec) o;
if (this.area() > m.area()){
return 1;
} else if(this.area() < m.area()) {
return -1;
}else return 0;
}
public String toString(){
return "(" + "边长为" + c + "和" + k + "面积为" + this.area() + ")";
}
}
public class TestSort {
public static void main (String [] args){
Stu [] a = new Stu [5];
a[0] = new Stu("ZhangSan",6);
a[1] = new Stu("LiSi",3);
a[2] = new Stu("WangWu",9);
a[3] = new Stu("ZhaoLiu",12);
a[4] = new Stu("QianQi",4);
sort (a);
for (int i=0; i<a.length; i++){
System.out.println("name="+ a[i].name + " " + "id=" + a[i].id);
}
Rec[] b = {new Rec(4,5), new Rec(7,2), new Rec(8,3), new Rec(2,11), new Rec(5,5)};
System.out.println();
Arrays.sort(a); //此为调用Arrays.sort()方法自动排序;
System.out.println("排序后"+Arrays.toString(a));
Arrays.sort(b);
System.out.println("排序后"+Arrays.toString(b));
}
}
class Stu implements Comparable{
String name;
int id;
public Stu (String n, int i){
name = n;
id = i;
}
public int compareTo(Object o){
Stu m = (Stu) o;
if (id > m.id){
return 1;
} else if(id < m.id){
return -1;
} else return 0;
}
public String toString(){
return "("+name+","+id+")";
}
}
class Rec implements Comparable{
int c, k;
public Rec (int m, int n){
c = m;
k = n;
}
int area (){
return c*k;
}
public int compareTo(Object o){
Rec m = (Rec) o;
if (this.area() > m.area()){
return 1;
} else if(this.area() < m.area()) {
return -1;
}else return 0;
}
public String toString(){
return "(" + "边长为" + c + "和" + k + "面积为" + this.area() + ")";
}
}
public class TestSort {
public static void main (String [] args){
Stu [] a = new Stu [5];
a[0] = new Stu("ZhangSan",6);
a[1] = new Stu("LiSi",3);
a[2] = new Stu("WangWu",9);
a[3] = new Stu("ZhaoLiu",12);
a[4] = new Stu("QianQi",4);
sort (a);
for (int i=0; i<a.length; i++){
System.out.println("name="+ a[i].name + " " + "id=" + a[i].id);
}
Rec[] b = {new Rec(4,5), new Rec(7,2), new Rec(8,3), new Rec(2,11), new Rec(5,5)};
System.out.println();
Arrays.sort(a); //此为调用Arrays.sort()方法自动排序;
System.out.println("排序后"+Arrays.toString(a));
Arrays.sort(b);
System.out.println("排序后"+Arrays.toString(b));
}
}
全部回答
- 1楼网友:持酒劝斜阳
- 2021-04-12 00:02
你的ID是什么类型的.可以根据ID字段的需求去找适合的解决方案
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯