比較子(Comparable、Comparator)類及 二叉樹的排序演算法!!__演算法

來源:互聯網
上載者:User

之前Arrays 類中存在sort() 方法, 此方法可以直接對 對象數組進行排序。

 1.Comparable介面

可以直接使用java.util.Arrays 類進行數組的排序操作,但對象所在的類必須實現Comparable 介面,用於指定排序介面。

Comparable 介面定義如下:

public interface Comparable<T>{

public int compareTo(T o);

}

此方法返回一個int 類型的資料,但是此int 的值只能是以下三種:

1:表示大於 

-1:表示小於

0:表示相等

要求:

定義一個學生類,裡面有姓名、年齡、成績三個屬性,要求按成績由高到低排序,如果成績相等,則按照年齡由低到高排序。

class Student implements Comparable<Student> {// 指定類型為Studentprivate String name ;private int age ;private float score ;public Student(String name,int age,float score){this.name = name ;this.age = age ;this.score = score ;}public String toString(){return name + "\t\t" + this.age + "\t\t" + this.score ;}public int compareTo(Student stu){// 覆寫compareTo()方法,實現定序的應用if(this.score>stu.score){return -1 ;}else if(this.score<stu.score){return 1 ;}else{if(this.age>stu.age){return 1 ;}else if(this.age<stu.age){return -1 ;}else{return 0 ;}}}};public class ComparableDemo01{public static void main(String args[]){Student stu[] = {new Student("張三",20,90.0f),new Student("李四",22,90.0f),new Student("王五",20,99.0f),new Student("趙六",20,70.0f),new Student("孫七",22,100.0f)} ;java.util.Arrays.sort(stu) ;// 進行排序操作for(int i=0;i<stu.length;i++){// 迴圈輸出數組中的內容System.out.println(stu[i]) ;}}};
2.分析比較子的排序原理

實際上比較子的操作,就是經常聽到的二叉樹的排序演算法。通過二叉樹進行排序,之後利用中序遍曆的方法把內容依次讀取出來。

排序的基本原理,使用第一個元素作為根節點,之後如果後面的內容比根節點要大,則放在左子樹,如果內容比根節點的內容要大,則放在右子樹。

下面就自己手式實現一個二叉樹的比較演算法。

為了操作方便,此處使用Integer 類完成。

public class ComparableDemo02{public static void main(String args[]){Comparable com = null ;// 聲明一個Comparable介面對象com = 30 ;// 通過Integer為Comparable執行個體化System.out.println("內容為:" + com) ;// 調用的是toString()方法}};
瞭解了此特性之後,下面就可以動物完成一個二叉樹演算法。

class BinaryTree{class Node{// 聲明一個節點類private Comparable data ;// 儲存具體的內容private Node left ;// 儲存左子樹private Node right ;// 儲存右子樹public Node(Comparable data){this.data = data ;}public void addNode(Node newNode){// 確定是放在左子樹還是右子樹if(newNode.data.compareTo(this.data)<0){// 內容小,放在左子樹if(this.left==null){this.left = newNode ;// 直接將新的節點設定成左子樹}else{this.left.addNode(newNode) ;// 繼續向下判斷}}if(newNode.data.compareTo(this.data)>=0){// 放在右子樹if(this.right==null){this.right = newNode ;// 沒有右子樹則將此節點設定成右子樹}else{this.right.addNode(newNode) ;// 繼續向下判斷}}}public void printNode(){// 輸出的時候採用中序遍曆if(this.left!=null){this.left.printNode() ;// 輸出左子樹}System.out.print(this.data + "\t") ;if(this.right!=null){this.right.printNode() ;}}};private Node root ;// 根項目public void add(Comparable data){// 加入元素Node newNode = new Node(data) ;// 定義新的節點if(root==null){// 沒有根節點root = newNode ;// 第一個元素作為根節點}else{root.addNode(newNode) ; // 確定是放在左子樹還是放在右子樹}}public void print(){this.root.printNode() ;// 通過根節點輸出}};public class ComparableDemo03{public static void main(String args[]){BinaryTree bt = new BinaryTree() ;bt.add(8) ;bt.add(3) ;bt.add(3) ;bt.add(10) ;bt.add(9) ;bt.add(1) ;bt.add(5) ;bt.add(5) ;System.out.println("排序之後的結果:") ;bt.print() ;}};
另一種比較子:Comparator

如果一個類已經開發完成,但是在此類建立的初期並沒有實現Comparable介面,此時肯定是無法進行對象排序操作的所以為瞭解決這樣的問題,java又定義了另一個比較子的操作介面——Comparator。

此介面定義在java.util 包中,介面定義如下:

public interface Comparator<T>{

public int compare(T o1, T o2);

boolean equals(Object obj);

}

下面定義一個自己的類,此類沒有實現Comparable介面。

import java.util.* ;class Student{// 指定類型為Studentprivate String name ;private int age ;public Student(String name,int age){this.name = name ;this.age = age ;}public boolean equals(Object obj){// 覆寫equals方法if(this==obj){return true ;}if(!(obj instanceof Student)){return false ;}Student stu = (Student) obj ;if(stu.name.equals(this.name)&&stu.age==this.age){return true ;}else{return false ;}}public void setName(String name){this.name = name ;}public void setAge(int age){this.age = age ;}public String getName(){return this.name ;}public int getAge(){return this.age ;}public String toString(){return name + "\t\t" + this.age  ;}};class StudentComparator implements Comparator<Student>{// 實現比較子// 因為Object類中本身已經有了equals()方法public int compare(Student s1,Student s2){if(s1.equals(s2)){return 0 ;}else if(s1.getAge()<s2.getAge()){// 按年齡比較return 1 ;}else{return -1 ;}}};public class ComparatorDemo{public static void main(String args[]){Student stu[] = {new Student("張三",20),new Student("李四",22),new Student("王五",20),new Student("趙六",20),new Student("孫七",22)} ;java.util.Arrays.sort(stu,new StudentComparator()) ;// 進行排序操作for(int i=0;i<stu.length;i++){// 迴圈輸出數組中的內容System.out.println(stu[i]) ;}}};

總結:

在使用中盡可以還是作用Comparable 在需要排序的類上實現好此介面,而Comparator 需要單獨建立一個排序的類,這樣如果有很多的話,則排序的規則類也就會非常多,操作起來比較麻煩。

掌握一點:只要是對象排序,則在javak 永遠是以Comparable 介面為準的。






聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.