Linux教程網
- import java.util.Arrays;
- import java.util.Comparator;
-
- public class TestSort {
-
- public static void main(String[] args) {
- TestSort ts = new TestSort();
-
- Integer[] it = new Integer[10];
- for (int i = 0; i < 10; i++) {
- it[i] = new Integer(10 - i);
- }
- ts.mergeSort(it, 0, it.length - 1, null);
- System.out.println(Arrays.toString(it));
- // 輸出結果為:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
-
- // 上面是對Integer對象進行排序
- /*************************************************************/
- // 下面是對Person對象進行排序
-
- PersonCompator pc = new PersonCompator();
- Person[] per = new Person[] { new Person(23, "a"), new Person(12, "b"),
- new Person(1, "c"), new Person(44, "d") };
- ts.mergeSort(per, 0, per.length - 1, pc);
- System.out.println(Arrays.toString(per));
- // 輸出結果為:[c:1, b:12, a:23, d:44]
- }
-
- /*
- * 對於對象比較有兩種方法,第一種是重寫此類,實現Compareable接口,Integer類就是這麼做的,
- * 所以此時可以直接將所有對象自動向上轉型為Object,再對其進行比較,進而排序
- *
- * 第二種則是寫一個此類的比較類,實現Comparator,下面的Person類就是這麼干的,此時只需調用 比較類的compare方法即可
- */
- private <T> void mergeSort(T[] arr, int i, int j, Comparator<? super T> c) {
- if (i < j) {
- int k = (i + j) / 2;
- mergeSort(arr, i, k, c);
- mergeSort(arr, k + 1, j, c);
- merge(arr, i, k, j, c);
- }
- }
-
- private <T> void merge(T[] arr, int p, int r, int q, Comparator<? super T> c) {
- int n1 = r - p + 1;
- int n2 = q - r;
- T[] L = arr.clone();
- System.arraycopy(arr, p, L, 0, n1);
- T[] R = arr.clone();
- System.arraycopy(arr, r + 1, R, 0, n2);
- int i = 0, j = 0, k = p;
- if (c == null) {
- while (i < n1 && j < n2) {
- if (((Comparable<T>) L[i]).compareTo(R[j]) <= 0) {
- arr[k++] = L[i++];
- } else {
- arr[k++] = R[j++];
- }
- }
- } else {
- while (i < n1 && j < n2) {
- if (c.compare(L[i], R[j]) <= 0) {
- arr[k++] = L[i++];
- } else {
- arr[k++] = R[j++];
- }
- }
- }
- while (i < n1) {
- arr[k++] = L[i++];
- }
- while (j < n2) {
- arr[k++] = R[j++];
- }
- }
- }
-
- class Person {
-
- private int age;
- private String name;
-
- public Person() {
-
- }
-
- public Person(int a, String n) {
- this.setAge(a);
- this.setName(n);
- }
-
- public int getAge() {
- return age;
- }
-
- public void setAge(int age) {
- this.age = age;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String toString() {
- return this.getName() + ":" + this.getAge();
- }
- }
-
- class PersonCompator implements Comparator<Person> {
- public int compare(Person o1, Person o2) {
- return o1.getAge() - o2.getAge();
- }
- }
Copyright ©
Linux教程網 All Rights Reserved