public class SortSelectionAlgorithm { public static <T extends Comparable<T>> T[] sortSelection(T arr[]){ if(arr!=null &&arr.length>0){ int n = arr.length; for (int i = 0; i < n; i++) { int minIndex = i; for(int j = i+1;j<n;j++){ if(arr[j].compareTo(arr[minIndex])<0){//则证明arrj<arrminindex minIndex = j; } swapArr(arr, minIndex, j); } } } return arr; } private static <T> void swapArr(T arr[],int aIndex,int bIndex){ T temp = null; temp = arr[aIndex]; arr[aIndex] = arr[bIndex]; arr[bIndex] = temp; } public static void main(String[] args) { /* Integer a[] = {10,9,8,7,6,5,4,3,2,1}; sortSelection(a); for (Integer integer : a) { System.out.println(integer); }*/ /* Student[] d = new Student[4]; d[0] = new Student("A",95); d[1] = new Student("B",95); d[2] = new Student("D",90); d[3] = new Student("E",91); sortSelection(d); for (Student student : d) { System.out.println(student.toString()); }*/ SortObject a[] = {new SortObject("A",9),new SortObject("B",9),new SortObject("C",8),new SortObject("E",8),new SortObject("D",6),new SortObject("F",5),new SortObject("G",4),new SortObject("H",3),new SortObject("I",2),new SortObject("J",1)}; sortSelection(a); for (SortObject sortObject : a) { System.out.println(sortObject.toString()); } } } public class SortObject implements Comparable<SortObject> { private String userName; private int age; public SortObject() { super(); // TODO Auto-generated constructor stub } public SortObject(String userName, int age) { super(); this.userName = userName; this.age = age; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "SortObject [userName=" + userName + ", age=" + age + "]"; } @Override public int compareTo(SortObject o) { // TODO Auto-generated method stub int result; System.out.println("this.userName== " + this.userName + ",o.userName== " + o.userName); if (this.age != o.age) { result = this.age - o.age; return result; } else { // this:arr[j] < o:arr[minIndex]result<0 if (!this.userName.equals(o.getUserName())) { result = this.userName.compareTo(o.userName);// this>o System.out.println("result=== " + result); return result; } else { return 0; } } } }
没找到哪里写的有问题,简单数组排序可实现,类排序 SortObject 在 age 相同,name 不同的时候排序不对,求解答
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于