Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. public class Selection {
  2. public static void sort(Comparable[] a) {
  3. int N = a.length;
  4. for (int i = 0; i < N; i++) {
  5. int min = i;
  6. for (int j = i + 1; j < N; j++) {
  7. if (less(a[j], a[min])) {
  8. min = j;
  9. }
  10. }
  11. if (min != i) {
  12. exch(a, i, min);
  13. }
  14. }
  15. }
  16.  
  17. // v 是否比 w 小 ? 如果返回 true: v < w
  18. private static boolean less(Comparable v, Comparable w) {
  19. return v.compareTo(w) < 0;
  20. }
  21.  
  22. private static void exch(Comparable[] a, int i, int j) {
  23. Comparable t = a[i];
  24. a[i] = a[j];
  25. a[j] = t;
  26. }
  27.  
  28. private static void show(Comparable[] a) {
  29. for (int i = 0; i < a.length; i++) {
  30. System.out.print(a[i] + " ");
  31. }
  32. System.out.println();
  33. }
  34.  
  35. public static boolean isSorted(Comparable[] a) {
  36. for (int i = 1; i < a.length; i++) {
  37. if (less(a[i], a[i - 1])) {
  38. return false;
  39. }
  40. }
  41. return true;
  42. }
  43.  
  44. public static void main(String[] args) {
  45. Comparable[] a = Utils.generateRandomIntArray(100, 0, 100);
  46. sort(a);
  47. assert isSorted(a);
  48. }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement