我正在尝试对二维数组进行排序。原始数组是
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;
}
}
}
它仍然没有排序,任何帮助将不胜感激。
看起来您正在尝试对数组中的行进行排序字典顺序 http://en.wikipedia.org/wiki/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);
希望这可以帮助!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)