排序在C 2维数组 [英] Sorting a 2 dimensional array in c

查看:140
本文介绍了排序在C 2维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想排序二维array.the原始数组

I am trying to sort a 2 dimensional array.the original array is

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

下面是code我曾经试图实现冒泡排序,我重新presents的行数。

Here is the code i used trying to implement Bubble Sort,i represents the number of rows.

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

它仍然不排序,任何帮助将大大AP preciated。

it still does not sort, any help will be greatly appreciated.

推荐答案

它看起来像你试图在的辞书订单。如果你把二维数组作为数组的数组,然后你只是排序第一级阵列中的第二级阵列升序字典顺序。

It looks like you are trying to sort the rows of the array in lexicographical order. If you treat the 2D array as an array of arrays, then you are just sorting the second-level arrays within the first-level array into ascending lexicographical order.

根据柱阵列的数量是固定的,你也许可以做到这一点使用的qsort 函数的自定义比较。例如,如果你知道总会有在每列正好3个元素,你可以写这样一个比较:

Depending on whether the number of columns in your array is fixed, you might be able to do this using the qsort function with a custom comparator. For example, if you know that there will always be exactly 3 elements in each column, you could write a comparator like this one:

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

希望这有助于!

这篇关于排序在C 2维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆