• 冒泡排序 (泛型版)


    /**

    *定义一个排序方法接口

    **/

    import java.util.Comparator;

    public interface Bubble {
        
        
        /**
         * 排序
         * @param list 待排序数组
         */
        public <T extends Comparable<T>> void sort(T[] list);
        /**
         * 排序
         * @param list 待排序数组
         * @param cmp 比较俩个对象的比较器
         */
        public <T> void sort(T[] list,Comparator<T> comp);
       
    }

    //实现方法接口

    import java.util.ArrayList;
    import java.util.Comparator;
    import java.util.stream.Stream;

    public class BubbleSort implements Bubble {
        

        @Override
        public <T extends Comparable<T>> void sort(T[] list) {
            boolean swapped = true;
            for (int i = 1, len = list.length; i < len && swapped; i++) {
                swapped = false;
                for (int j = 0; j < len - i; j++) {
                    if (list[j].compareTo(list[j + 1]) > 0) {
                        T temp = list[j];
                        list[j] = list[j + 1];
                        list[j + 1] = temp;
                        swapped = true;
                    }
                }
            }

        }

        

        @Override
        public <T> void sort(T[] list, Comparator<T> comp) {
            boolean swapped = true;
            for (int i = 1, len = list.length; i < len && swapped; i++) {
                swapped = false;
                for (int j = 0; j < len - i; j++) {
                    if (comp.compare(list[j], list[j + 1]) > 0) {
                        T temp = list[j];
                        list[j] = list[j + 1];
                        list[j + 1] = temp;
                        swapped = true;
                    }
                }

            }
            
        }

    }

    //测试类

    package sort;
    public class TeatSort {
        
        
        
        public static void main(String[] args){
            Integer[] list={1,2,31,2,15,68};
            new BubbleSort().sort(list,(o1,o2)->{
                 if(o1>o2)
                     return 1;
                   else
                       return 0;
            });
            for(int i=0;i<list.length;i++){
                System.out.println(list[i].intValue());
            }
            String[] listStr={"1","8","4","6","9"};
            new BubbleSort().sort(listStr);
            for(int i=0;i<listStr.length;i++){
                System.out.println(listStr[i]);
            }
        }

    }

  • 相关阅读:
    Memcached 常用命令及使用说明
    Linux 搭建svn版本库
    实现word在线预览 有php的写法 也有插件似
    mysql引擎
    memcache的addServer的故障转移机制
    php伪静态配置
    使用MySQL的慢查询日志找到低效的SQL语句
    使用Snoopy进行模拟登陆、采集
    在线播放mp3代码(dewplayer)
    使用php发送电子邮件(phpmailer)
  • 原文地址:https://www.cnblogs.com/smallbrokenchildwen/p/6744737.html
Copyright © 2020-2023  润新知