herrDeng網內搜尋

自訂搜尋

Ads

2011年12月8日 星期四

如何利用實作Interface Comparator來sort, binaySearch

如何利用實作Interface Comparator來sort, binaySearch


import java.util.*;
import java.util.Arrays;

class student
{
    String name;
    int number;
    student(String name, int number)
    {
         this.name=name;
         this.number=number;
     }
    void printData()
   {
        System.out.print(name+'\t');
        System.out.println(number);
    }
 }
 class studentComparator implements Comparator<student> {
     public int compare(student X1, student X2)
   {
       return X1.number-X2.number;
    }
}
class SortStudent{
    public static void main(String argv[]){
    student X[]=new student[10];
    for (int i=0; i<=9; i++)
   {
      X[i]=new student("學生"+i, (int)(100*Math.random()));
      X[i].printData();
   }
  studentComparator C=new studentComparator();
  Arrays.sort(X, C);
  System.out.println("排序後");
  for (int i=0; i<=9; i++)
  {
   X[i].printData();
   }
  student key=new student("學生"+0,50);
  System.out.println(Arrays.binarySearch(X,key,C));
 }
}

//http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html
//http://download.oracle.com/javase/6/docs/api/java/util/Comparator.html
Related Posts Plugin for WordPress, Blogger...

熱門文章