You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java自定义归并排序:按Ball对象字段选择Comparator排序

修改归并排序以支持自定义Comparator排序

要让你的归并排序支持按不同字段排序,只需要把Comparator<Ball>传递到排序方法中,替换原有硬编码的整数比较逻辑即可,具体修改步骤如下:

1. 给排序方法添加Comparator参数

给对外暴露的mergeSort方法以及递归用的mergeSortInner方法新增Comparator<Ball>参数,让比较逻辑可以从外部传入。

2. 替换合并阶段的比较逻辑

把原来合并时的整数比较sorted1[index1] < sorted2[index2],替换为调用Comparator的compare方法判断大小:comparator.compare(sorted1[index1], sorted2[index2]) < 0(Comparator的compare方法返回负数表示前者小于后者)。

修改后的完整TypeMergeSort代码

import java.util.Arrays;
import java.util.Comparator;

public class TypeMergeSort {
    // 对外暴露的排序方法,接收待排序数组和对应的比较器
    public static Ball[] mergeSort(Ball[] list, Comparator<Ball> comparator) {
        Ball[] buffer1 = Arrays.copyOf(list, list.length);
        Ball[] buffer2 = new Ball[list.length];
        Ball[] result = mergeSortInner(buffer1, buffer2, 0, list.length, comparator);
        return result;
    }

    // 递归内部方法,新增Comparator参数
    private static Ball[] mergeSortInner(Ball[] buffer1, Ball[] buffer2, int startIndex, int endIndex, Comparator<Ball> comparator) {
        if (startIndex >= endIndex - 1) {
            return buffer1;
        }

        int middle = startIndex + (endIndex - startIndex) / 2;
        // 递归调用时传入比较器
        Ball[] sorted1 = mergeSortInner(buffer1, buffer2, startIndex, middle, comparator);
        Ball[] sorted2 = mergeSortInner(buffer1, buffer2, middle, endIndex, comparator);

        int index1 = startIndex;
        int index2 = middle;
        int destIndex = startIndex;

        Ball[] result = sorted1 == buffer1 ? buffer2 : buffer1;

        // 使用Comparator的compare方法替代原整数比较逻辑
        while (index1 < middle && index2 < endIndex) {
            result[destIndex++] = comparator.compare(sorted1[index1], sorted2[index2]) < 0
                    ? sorted1[index1++] : sorted2[index2++];
        }
        while (index1 < middle) {
            result[destIndex++] = sorted1[index1++];
        }
        while (index2 < endIndex) {
            result[destIndex++] = sorted2[index2++];
        }

        return result;
    }
}

3. 调用示例

现在可以通过传入不同的Comparator实现按不同字段排序:

按重量排序

Ball[] balls = {new Ball(5, 30, "red"), new Ball(3, 10, "blue"), new Ball(4, 20, "green")};
Ball[] sortedByWeight = TypeMergeSort.mergeSort(balls, new SortByWeight());

按颜色排序

Ball[] sortedByColor = TypeMergeSort.mergeSort(balls, new SortByColor());

额外说明

这种方式实现了排序算法和比较逻辑的解耦,以后如果需要按size字段排序,只需要新增一个SortBySize类实现Comparator<Ball>即可,完全不需要修改归并排序的核心代码,符合开闭原则。

内容的提问来源于stack exchange,提问作者Anton Kolb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 00:45:41