【问题标题】:Sorting a 2 dimensional array in c在c中对二维数组进行排序
【发布时间】:2026-02-13 18:55:01
【问题描述】:

我正在尝试对二维数组进行排序。原始数组是

5 0 3
4 1 2
3 1 1
4 2 2
3 3 1

排序的时候应该是这样的

3 1 1
3 3 1
4 2 2
4 1 2
5 0 3

这是我用来实现冒泡排序的代码,i代表行数。

int x,y,z,j,temp1,temp2,temp3;
for(x=0;x<i;x++)
{
    for (j=0;j<i-1;j++)
    {
        if(a[j][0]>a[j+1][0])
        {
            temp1=a[j][0];
            temp2=a[j][1];
            temp3=a[j][2];
            a[j][0]=a[j+1][0];
            a[j][1]=a[j+1][1];
            a[j][2]=a[j+1][2];
            a[j+1][0]=temp1;
            a[j+1][1]=temp2;
            a[j+1][2]=temp3;
        }
    }
}

它仍然没有排序,任何帮助将不胜感激。

【问题讨论】:

  • 你的括号风格很奇怪。
  • 为什么4 2 2 出现在4 1 2 之前?
  • 一个很好的提示是不要在循环之外使用变量x
  • 您要对行或列进行排序吗?
  • 如果您根据第一列排序,那么您只是对一维数组进行排序。很多算法..

标签: c arrays sorting multidimensional-array


【解决方案1】:

您似乎正在尝试对 lexicographical order 中的数组行进行排序。如果您将二维数组视为数组数组,那么您只是将一级数组中的二级数组按字典升序排序。

根据数组中的列数是否固定,您可以使用带有自定义比较器的qsort 函数来执行此操作。例如,如果你知道每列总是正好有 3 个元素,你可以写一个像这样的比较器:

static const size_t NUM_COLS = 3;

/* Lexicographically compare two arrays of size NUM_COLS. */
int CompareArrays(const void* arr1, const void* arr2) {
     /* Convert back to the proper type. */
     const int* one = (const int*) arr1;
     const int* two = (const int*) arr2;

     /* Do an element-by-element comparison.  If a mismatch is found, report how
      * the arrays compare against one another.
      */
     for (size_t i = 0; i < NUM_COLS; i++) {
         if (one[i] < two[i]) return -1;
         if (one[i] > two[i]) return +1;
     }

     /* If we get here, the arrays are equal to one another. */
     return 0;
}

/* Use qsort to sort the arrays */
qsort((const int*)&one, numRows, sizeof(int[NUM_COLS]), CompareArrays);

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    在c中排序二维数组

    int x[5][5],i,j,i1,j1,temp,k;
    
    for (int i=0;i<5;i++)
    for (int j=0:<5;j++)
     cin>>x[i][j];
    
    
     for (int i=0;i<5;i++)
       for (int j=0:<5;j++)
    {
        k=j+1;
                for (int i1=0;i<5;i1++)
                {
                    for (int j1=k:<5;j1++)
                        {
                        if (x[i,j]>x[i1,j1])
                            {
                            temp=x[i,j];
                            x[i,j]=x[i1,j1];
                            x[i1,j1]=temp;
                            }
                         }
                    k=1;
                }
    }
    
    
    for (int i=0;i<5;i++)
    for (int j=0:<5;j++)
     cout<<x[i][j];
    

    【讨论】: