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

如何用同一个函数实现二维数组的行排序与列排序?

复用一维排序函数实现二维数组列排序的修改方案

嘿,这个问题的核心其实是搞懂原排序函数的工作逻辑——它是针对连续内存中的一维int数组做选择排序的,行排序能直接复用是因为每行的元素在内存里是连续的,但同一列的元素在内存中是分散的(每行同列元素之间隔了m个int的位置),所以原函数没法直接处理。下面给你两种可行的方案,按需选择:

方案1:修改原sort函数,增加步长参数

我们可以给原排序函数加一个step(步长)参数,用来指定下一个待比较元素的内存偏移量。这样就能处理非连续的元素序列(比如二维数组的列)。

修改后的排序函数

void sort(int *a, int n, int step) {
    int temp;
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            // 通过步长定位到列中的对应元素
            if (*(a + i*step) > *(a + j*step)) {
                temp = *(a + j*step);
                *(a + j*step) = *(a + i*step);
                *(a + i*step) = temp;
            }
        }
    }
}

调用方式(实现列排序)

对于n行m列的二维数组b,遍历每一列,传入该列的第一个元素地址、行数n和步长m:

for (int col = 0; col < m; col++) {
    // &b[0][col] 是第col列第一个元素的地址
    sort(&b[0][col], n, m);
}

这里的步长m表示:每往后找一个同列元素,需要跳过m个int的内存空间(也就是跳到下一行的同一列)。

方案2:不修改原sort函数,临时转存列元素

如果你不想改动原有的排序函数,完全可以用“中转数组”的方式:把每一列的元素先复制到一个临时一维数组里,用原sort排序后再写回原二维数组的对应列。

实现代码

#include <stdlib.h> // 用于malloc和free

// 对n行m列的二维数组b实现列排序
void sort_columns(int b[][m], int n, int m) {
    int *temp_arr = (int*)malloc(n * sizeof(int));
    if (temp_arr == NULL) {
        // 处理内存分配失败的情况,比如打印错误信息
        printf("Memory allocation failed!\n");
        return;
    }

    for (int col = 0; col < m; col++) {
        // 1. 把当前列的元素复制到临时数组
        for (int row = 0; row < n; row++) {
            temp_arr[row] = b[row][col];
        }
        // 2. 用原sort函数排序临时数组
        sort(temp_arr, n);
        // 3. 把排序后的元素写回原列
        for (int row = 0; row < n; row++) {
            b[row][col] = temp_arr[row];
        }
    }

    free(temp_arr); // 释放临时内存
}

优缺点

  • 优点:完全复用原sort函数,不需要修改原有代码逻辑,兼容性好。
  • 缺点:需要额外的内存空间存储临时数组,并且多了两次元素复制的操作,当n很大时会有一定的性能开销。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 03:53:38