功能样式Java 8中的冒泡排序 [英] Bubble sort in functional style Java 8

查看:57
本文介绍了功能样式Java 8中的冒泡排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您将如何以功能性(Java 8)方式实现以下冒泡排序算法?

How would you implement the following Bubble Sort algorithm in a functional (Java 8) way?

public static final <T extends Comparable<T>> List<T> imperativeBubbleSort(List<T> list) {
    int len = list == null ? 0 : list.size();
    for (int j = len - 1; j > 0; j--) {
        for (int k = 0; k < j; k++) {
            if (list.get(k + 1).compareTo(list.get(k)) < 0) {
                list.add(k, list.remove(k + 1));
            }
        }
    }
    return list;
}

推荐答案

这取决于您所说的功能.如果您只是想将函数作为第一类对象传递,则应将方法签名更改为:

It would depend on what you mean by functional. If you mean just passing around functions as first class objects, then you should change your method signature to be:

public static final <T> List<T> imperativeBubbleSort(List<T> list, Comparator<T> comparisonFunction)

这样,比较逻辑可以作为参数提供.

This way the comparison logic can be supplied as an argument.

如果您的意思是完全发挥功能而不是完全不执行程序,那么我将其称为反模式.尽管您可能听到了什么,但是Java 8并不完全支持函数式编程.它缺少的一个关键功能是尾部呼叫优化.没有它,定义功能性编程的那种无环编程可能会使JVM相对较小的值崩溃.

If you mean going fully functional and not at all procedural, then I would call it an anti-pattern. Despite what you might hear, Java 8 does not fully support functional programming. A key feature that it is missing is tail-call optimization. Without it, the sort of loop-less programming that defines functional programming is likely to crash your JVM for relatively small values.

有关尾部调用优化和JVM的更多信息,可以在这里找到:

More information about tail call optimizations and the JVM can be found here: http://www.drdobbs.com/jvm/tail-call-optimization-and-java/240167044

这篇关于功能样式Java 8中的冒泡排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆