java中sort方法的自定義比較器寫法

常用JAVA API和基礎算法合集:
https://blog.csdn.net/GD_ONE/article/details/104061907

摘要

在做一些算法題時常常會需要對數組、自定義對象、集合進行排序. 在java中對數組排序提供了Arrays.sort()方法,對集合排序提供Collections.sort()方法。對自定義對象排序時要自己重寫比較器,對象數組則調用Arrays.sort(),對象集合則調用Collections.sort()。兩個方法默認都是升序,也可以重寫比較器,實現降序。

對數組排序

sort函數模板, 以int型數組爲例:

Arrays.sort(int[] a, Comparator<Integer>() {
	public int compare(int a, int b){
		 return a - b;   升序
		// return b - a;   降序
		// a - b > 0 交換ab位置,反之不變, 即返回值爲正數時,交換數組中正在比較的
		//兩個元素的位置,返回值爲負數時,不交換。 
		}
	})

例題: 快速排序

給定你一個長度爲n的整數數列。

請你使用快速排序對這個數列按照從小到大進行排序。

並將排好序的數列按順序輸出。

輸入格式
輸入共兩行,第一行包含整數 n。

第二行包含 n 個整數(所有整數均在1~109範圍內),表示整個數列。

輸出格式
輸出共一行,包含 n 個整數,表示排好序的數列。

數據範圍
1≤n≤100000
輸入樣例:
5
3 1 2 4 5
輸出樣例:
1 2 3 4 5

可以將字符串數組轉化爲整型數組之後在排序,爲了演示自定義比較器的寫法這裏直接對字符串數組進行排序

import java.io.*;
import java.util.*;

public class Main{
	// 輸入輸出模板
	static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
	
	static int n;
	public static void main(String[] args) throws IOException {
		n = Integer.parseInt(in.readLine());
		String s[] = in.readLine().split(" ");// 讀入數據
		
		Arrays.sort(s, new Comparator<String>() { // 排序
			public int compare(String a, String b) {  
	        	if(a.length() == b.length()){ // 如果長度相等則直接比較字典序
	        		return a.compareTo(b);
	        	}
	        	else{ // 長度長的一定大
	        		return a.length() - b.length();
	        	}
			}
		});
		
		for(String p : s){
			out.write(p+" ");
		}
		
		out.flush();
	}
}

對集合進行排序

創建TreeSet實例,對其從大到小排序。
因爲TreeSet是自動排序和去重的, 默認爲升序,我們可以重寫比較器構造一個降序的TreeSet, 之後添加數據就會自動排序。

import java.io.*;
import java.util.*;

public class Main{
	static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
	
	public static void main(String[] args) throws IOException {
		
		TreeSet<Integer> s = new TreeSet<>(new Comparator<Integer>(){
			public int compare(Integer a, Integer b) {  
	        	return b - a; 
			}
		});
		
		s.add(10);
		s.add(5);
		s.add(4);
		s.add(6);
		s.add(7);
		s.add(8);
		s.add(1);
		s.add(2);
		s.add(3);
		s.add(9);
		
		for(Integer p : s){
			out.write(p+" ");
		}
		out.flush();
	}
}
輸出:
10 9 8 7 6 5 4 3 2 1

對自定義對象數組排序

創建學生類, 按照年齡從小到大排序

import java.io.*;
import java.util.*;

class student{ 
	int age;
	String name;
	student(int a, String b){
		this.age = a;
		this.name = b;
	}
}
public class Main{
	static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
	
	public static void main(String[] args) throws IOException {
		student s[] = new student[4]; //創建學生對象數組
		s[0] = new student(10, "1");
		s[1] = new student(9, "2");
		s[2] = new student(8, "3");
		s[3] = new student(7, "4");
		
		Arrays.sort(s, new Comparator<student>() {
			public int compare(student a, student b) {  //
	        	return a.age - b.age; // 按照年齡大小升序排列
			}
		});
		for(student p : s){
			out.write(p.age+" "+p.name + "\n");
		}
		out.flush();
	}
}

輸出:
7 4
8 3
9 2
10 1

大致就是這樣了,還可以對要排序的類實現Comparable接口,重寫compareTo方法。
代碼:


//對pair類實現Comparable接口後,直接調用sort函數排序就行了。
static class pair implements Comparable<pair>{
        int a, b, w;
        pair(int u, int v, int x){
            a = u;
            b = v;
            w = x;
        }
        public int compareTo(pair p) {
    		return this.w - p.w;
    	}
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章