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

Java中实现int与float数组的并行排序(低内存开销方案)

同步排序关联数组的解决方案

针对你提出的需求——在不封装自定义对象、复用JVM标准排序算法的前提下,同步排序两个关联的大数组,可通过索引数组排序法实现,具体步骤如下:

  • 生成索引数组:创建一个与原数组等长的int数组,存储0到数组长度-1的索引值,这个数组的内存开销极小(每个元素仅4字节),完全适配内存限制要求。
  • 按关联规则排序索引数组:使用Arrays.sort()的重载版本,传入自定义Comparator,根据myInt中对应索引的元素值对索引数组排序。
  • 基于排序后的索引数组同步调整原数组:可选择创建新数组存储结果,或通过原地交换的方式修改原数组(避免额外内存开销)。

代码示例

import java.util.Arrays;

public class SyncSortExample {
    public static void main(String[] args) {
        int[] myInt = {1, 3, 2};
        float[] myFloat = {0.5f, 0.4f, 0.3f};
        int length = myInt.length;

        // 1. 创建索引数组
        int[] indices = new int[length];
        for (int i = 0; i < length; i++) {
            indices[i] = i;
        }

        // 2. 按myInt的元素值对索引数组排序
        Arrays.sort(indices, (a, b) -> Integer.compare(myInt[a], myInt[b]));

        // 方式一:创建新数组存储排序结果(内存允许时使用)
        int[] sortedInt = new int[length];
        float[] sortedFloat = new float[length];
        for (int i = 0; i < length; i++) {
            sortedInt[i] = myInt[indices[i]];
            sortedFloat[i] = myFloat[indices[i]];
        }
        // 此时sortedInt为{1,2,3},sortedFloat为{0.5f,0.3f,0.4f}

        // 方式二:原地修改原数组(无额外内存开销)
        boolean[] processed = new boolean[length];
        for (int i = 0; i < length; i++) {
            if (processed[i]) continue;
            int current = i;
            while (!processed[current]) {
                processed[current] = true;
                int next = indices[current];
                if (next == i) break;
                // 同步交换myInt的元素
                int tempInt = myInt[i];
                myInt[i] = myInt[next];
                myInt[next] = tempInt;
                // 同步交换myFloat的元素
                float tempFloat = myFloat[i];
                myFloat[i] = myFloat[next];
                myFloat[next] = tempFloat;
                current = next;
            }
        }
        // 此时myInt和myFloat已完成同步排序
    }
}

核心说明

Java标准库并未提供直接支持自定义交换逻辑的排序API,但通过索引数组的方式,我们可以复用Arrays.sort()的优化实现(底层为双枢轴快速排序,性能优异),同时避免封装自定义对象带来的内存开销,完美适配你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 02:43:23