• Java、泛型冒泡排序


     

    1. package sort;
    2. import java.security.SecureRandom;
    3. import java.util.Arrays;
    4. import java.util.Comparator;
    5. /**
    6. * @author: xyz
    7. * @create: 2022/8/14
    8. * @Description:
    9. * @FileName: Exercise23_01
    10. * @History:
    11. * @自定义内容:
    12. */
    13. public class Exercise23_01 {
    14. public static void main(String[] args) {
    15. Integer[] list1 = new Integer[10];
    16. for (int i = 0; i < list1.length; i++)
    17. list1[i] = new SecureRandom().nextInt(20);
    18. System.out.println(Arrays.toString(list1));
    19. bubbleSort(list1, new SortComparator<>());
    20. System.out.println(Arrays.toString(list1));
    21. String[] list2 = {"China", "Babylon", "Paris", "america", "India", "Japan"};
    22. System.out.println(Arrays.toString(list2));
    23. bubbleSort(list2);
    24. System.out.println(Arrays.toString(list2));
    25. Double[] list3 = new Double[10];
    26. for (int i = 0; i < list3.length; i++)
    27. list3[i] = Math.random() * 20;
    28. System.out.println(Arrays.toString(list3));
    29. bubbleSort(list3, new SortComparator<>());
    30. System.out.println(Arrays.toString(list3));
    31. }
    32. /** 使用Comparable接口的泛型冒泡排序 */
    33. public static extends Comparable> void bubbleSort(E[] list) {
    34. for (int i = 1; i < list.length; i++) {
    35. for (int j = 0; j < list.length - i; j++)
    36. if (list[j].compareTo(list[j + 1]) > 0) {
    37. E temp = list[j];
    38. list[j] = list[j + 1];
    39. list[j + 1] = temp;
    40. }
    41. }
    42. }
    43. /** 使用Comparator接口的泛型冒泡排序 */
    44. public static void bubbleSort(E[] list, Comparatorsuper E> comparator) {
    45. for (int i = 1; i < list.length; i++) {
    46. for (int j = 0; j < list.length - i; j++)
    47. if (comparator.compare(list[j], list[j + 1]) > 0) {
    48. E temp = list[j];
    49. list[j] = list[j + 1];
    50. list[j + 1] = temp;
    51. }
    52. }
    53. }
    54. /** 静态内部类-泛型比较器类 */
    55. static class SortComparator implements Comparator {
    56. @Override
    57. public int compare(E o1, E o2) {
    58. if (o1 instanceof Comparable) {
    59. if (((Comparable) o1).compareTo(o2) > 0) return 1;
    60. else if (((Comparable) o1).compareTo(o2) < 0) return -1;
    61. else return 0;
    62. }
    63. //按哈希码排序
    64. if (o1.hashCode() > o2.hashCode())
    65. return 1;
    66. else if (o1.hashCode() < o2.hashCode())
    67. return -1;
    68. else
    69. return 0;
    70. }
    71. }
    72. }

     

  • 相关阅读:
    Nacos相关面试题
    面试(类加载器)
    【Codeforces】Educational Codeforces Round 156 [Rated for Div. 2]
    TRC丨艾美捷 TRC阿托伐他汀-d5钠盐说明书
    【集训DAY N】火车【LCA】【模拟】
    3-知识补充-MVC框架
    【Python笔记-设计模式】迭代器模式
    海螺问问编写shell脚本zabbix监控华为设备微信接入预警
    IAM、EIAM、CIAM、RAM、IDaaS 都是什么?
    【vscode远程开发】使用内网穿透实现在公网环境下远程访问
  • 原文地址:https://blog.csdn.net/m0_62659797/article/details/126375136