首页 > 其他 > 详细

sort utility

时间:2014-08-05 15:43:29      阅读:450      评论:0      收藏:0      [点我收藏+]

 

 

Create an interface called Sortable in a package called sortPack. It should have one method compare which takes an Object as a parameter and returns an integer. In the same package create a class called Sort with a static method called sortAny which takes a Sortable array as a parameter. It sorts the array using the compare method in Sortable.

Create a class called NewPerson which implements Sortable and give the concrete implementation of the compare method.

In another class write a main to use the above sort utility.

 

1 package sortPack;
2 
3 interface  Sortable {
4     int compare(Object o);
5 }

 

 1 package sortPack;
 2 
 3 public class NewPerson implements Sortable {
 4     int ID;
 5 
 6     public NewPerson(int ID) {
 7         this.ID = ID;
 8     }
 9 
10     public int getID() {
11         return ID;
12     }
13 
14     public int compare(Object o) {
15         int res = 1;
16 
17         if (this.ID > ((NewPerson) o).ID)
18             return 0;
19         return res;
20     }
21 
22 }

 

 1 package sortPack;
 2 
 3 import java.util.Arrays;
 4 
 5 public class Sort {
 6     
 7     static  void sortAny (Sortable arr[]){
 8         Sortable temp;
 9         for(int i=0;i<arr.length-1;i++){
10             for(int j=i+1;j<arr.length;j++){
11                 if((arr[i]).compare(arr[j])==0){
12                     temp=arr[i];
13                     arr[i]=arr[j];
14                     arr[j]=temp;
15                 }
16         }
17         }
18         
19     }
20 }

 

 

 1 package sortPack;
 2 
 3 public class TestSort {
 4 
 5     public static void main(String[] args) {
 6         
 7        NewPerson[] person = { new NewPerson(123), 
 8                                new NewPerson(128),
 9                                new NewPerson(111), 
10                                new NewPerson(121), 
11                                new NewPerson(113),
12                                new NewPerson(101), 
13                                new NewPerson(116) };
14         System.out.println("Before Sort:");
15         for(NewPerson per:person){
16             System.out.print(per.getID()+"  ");
17         }
18         Sort.sortAny(person);
19         
20         System.out.println("\nAfter  Sort:");        
21         for(NewPerson per:person){
22             System.out.print(per.getID()+"  ");
23         }
24 
25     }
26 
27 }

 

 

bubuko.com,布布扣

sort utility,布布扣,bubuko.com

sort utility

原文:http://www.cnblogs.com/thrive/p/3892317.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!