Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Selection {
- public static void sort(Comparable[] a) {
- int N = a.length;
- for (int i = 0; i < N; i++) {
- int min = i;
- for (int j = i + 1; j < N; j++) {
- if (less(a[j], a[min])) {
- min = j;
- }
- }
- if (min != i) {
- exch(a, i, min);
- }
- }
- }
- // v 是否比 w 小 ? 如果返回 true: v < w
- private static boolean less(Comparable v, Comparable w) {
- return v.compareTo(w) < 0;
- }
- private static void exch(Comparable[] a, int i, int j) {
- Comparable t = a[i];
- a[i] = a[j];
- a[j] = t;
- }
- private static void show(Comparable[] a) {
- for (int i = 0; i < a.length; i++) {
- System.out.print(a[i] + " ");
- }
- System.out.println();
- }
- public static boolean isSorted(Comparable[] a) {
- for (int i = 1; i < a.length; i++) {
- if (less(a[i], a[i - 1])) {
- return false;
- }
- }
- return true;
- }
- public static void main(String[] args) {
- Comparable[] a = Utils.generateRandomIntArray(100, 0, 100);
- sort(a);
- assert isSorted(a);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement