你知道怎么在排序算法中使用策略模式吗?

抽点时间简单回顾下八大排序算法中的冒泡 。。毕竟其他也记不住 哈哈哈哈
在这里插入图片描述

使用策略模式来实现,策略模式使用范围也很广,如省略一堆 if else

一般用在。。额 等找到笔记再补上

在这里插入图片描述

一。定义一个抽象类

/**
 * 之所以定义成 抽象类 而不是接口 只是为了少写点代码,加入name 属性 哈哈哈
 */
abstract class SortStrategy {
    
    
    String name;

    abstract int[] sortArr(int[] arr);

    String getName() {
    
    
        return this.name;
    }
}

二。重写抽象类中的方法

/**
 * 冒泡排序(Bubble Sort)
 * 比较相邻的元素。如果第一个比第二个大,就交换他们两个。
 * 再比较2,3...
 * <p>
 * 平均时间复杂度	最好情况	最坏情况	空间复杂度
 * O(n²)	O(n)	O(n²)	O(1)
 * <p>
 * 冒泡排序是最容易实现的排序, 最坏的情况是每次都需要交换, 共需遍历并交换将近n²/2次, 时间复杂度为O(n²).
 * 最佳的情况是内循环遍历一次后发现排序是对的, 因此退出循环, 时间复杂度为O(n).
 * 平均来讲, 时间复杂度为O(n²). 由于冒泡排序中只有缓存的temp变量需要内存空间, 因此空间复杂度为常量O(1).
 * <p>
 * 由于冒泡排序只在相邻元素大小不符合要求时才调换他们的位置, 它并不改变相同元素之间的相对顺序, 因此它是稳定的排序算法。
 */
class BubbleSortStrategy extends SortStrategy {
    
    

    public BubbleSortStrategy(String name) {
    
    
        this.name = name;
    }


    @Override
    public int[] sortArr(int[] arr) {
    
    
        for (int i = 0; i < arr.length - 1; i++) {
    
    
            for (int j = 0; j < arr.length - 1 - i; j++) {
    
    
                if (arr[j] > arr[j + 1]) {
    
    
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        return arr;
    }
}

三。按需使用

public class OrderTest {
    
    

    void takeTime(SortStrategy sortStrategy, int[] arr) {
    
    
        StopWatch stopWatch = new StopWatch();
        stopWatch.start(sortStrategy.getName());
        int[] ints = sortStrategy.sortArr(arr);
        System.out.println(Arrays.toString(ints));
        stopWatch.stop();
//      1ms=1 000 000 ns
        System.out.println(stopWatch.getLastTaskName()
                + "[take time ns] : " + stopWatch.getLastTaskTimeNanos());
    }

    @Test
    void testOrder() {
    
    
        int[] arr = {
    
    10, 3, 6, 4, 7, 5, 1, 2, 8, 9};
        takeTime(new BubbleSortStrategy("BubbleSortStrategy"), arr);
    }

}

滴 水文成功卡!哈哈哈
在这里插入图片描述
您的关注,是博主生发的动力呀!
wechat

猜你喜欢

转载自blog.csdn.net/weixin_40251892/article/details/111473308