Javaの:ソート

ソート

通常の配列のソート

public class Main {
	public static int n;
	public static int N = 100005;
	public static int a[] = new int[N];
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		for(int i = 1; i <= n; i++) {
			a[i] = sc.nextInt();
		}
		Arrays.sort(a, 1, n + 1);
		for(int i = 1; i <= n; i++) {
			if(i > 1) System.out.print(" ");
			System.out.print(a[i]);
		}
	}
}

(また、ライン上に出力を後方、前方に並べ替えることができる)降順を実現するCMP

class shu {
	int x;
}
class cmp implements Comparator<shu> {
	public int compare(shu A, shu B) {
		return B.x - A.x; // 按从大到小排序
	}
}
public class Main {
	public static int n;
	public static int N = 100005;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		shu a[] = new shu[N]; // 创建类数组
		for(int i = 1; i <= n; i++) {
			a[i] = new shu(); // 初始化,实例化
			a[i].x = sc.nextInt();
		}
		Arrays.sort(a, 1, n + 1, new cmp());
		for(int i = 1; i <= n; i++) {
			if(i > 1) System.out.print(" ");
			System.out.print(a[i].x);
		}
	}
}

複数の値をソートする:異なるスコア、降順スコアを押し、同じスコア場合、辞書ソート文字列を押します。

class node {
	String name;
	int score;
}
class cmp implements Comparator<node> {
	public int compare(node A, node B) {
		if(A.score != B.score) {
			return B.score - A.score; // 分数从高到低
		} else {
			return A.name.compareTo(B.name); // 字典序从小到大
		}
	}
}

注:以下に示すように配列の長さの異なるタイプ、結果を区別します。

public class practice {
	static Scanner sc = new Scanner(System.in);
	static int N = 1005;
	static int a[] = new int[N];
	static double b[] = new double[N];
	static float c[] = new float[N];
	static char s[] = new char[N];
	public static void main(String[] args) {
		System.out.println("int型的数组长度:" + a.length);
		System.out.println("double型的数组长度:" + b.length);
		System.out.println("float型的数组长度:" + c.length);
		String str = new String(sc.next());
		s = str.toCharArray();
		System.out.println("char型的数组长度:" + s.length);
	}
}

公開された150元の記事 ウォンの賞賛4 ビュー6915

おすすめ

転載: blog.csdn.net/Napom/article/details/104152623