在C语言中对二维数组进行排序

5

我正在尝试对一个二维数组进行排序。原始数组如下:

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;
        }
    }
}

它仍然没有排序,非常感谢您的任何帮助。


13
你的括号使用方式很奇特。 - moonwave99
9
为什么4 2 2排在4 1 2前面? - pmg
1
一个好的提示是不要在循环之外使用变量 x - Hogan
2
如果您按照第一列进行排序,则只是对一维数组进行排序。有很多算法可以实现这个功能。 - asheeshr
更改了。格式让我头疼。 - WhozCraig
显示剩余2条评论
2个回答

3

看起来你正在尝试按字典顺序排序数组的行。如果将2D数组视为数组的数组,则只需将一级数组中的二级数组按升序字典顺序排序。

根据数组中列数是否固定,你可以使用带有自定义比较器的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);

希望这能帮到你!

-1

在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];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接