sos*_*tee 5 c arrays sorting multidimensional-array
我正在尝试对二维数组进行排序.原始数组是
5 0 3
4 1 2
3 1 1
4 2 2
3 3 1
Run Code Online (Sandbox Code Playgroud)
排序时,应该是这样的
3 1 1
3 3 1
4 2 2
4 1 2
5 0 3
Run Code Online (Sandbox Code Playgroud)
这是我用来尝试实现冒泡排序的代码,我代表行数.
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
它仍然没有排序,任何帮助将不胜感激.
看起来您正在尝试按字典顺序对数组的行进行排序。如果将二维数组视为数组的数组,那么您只需将第一级数组中的第二级数组按字典升序排序。
根据数组中的列数是否固定,您也许可以使用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);
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
11013 次 |
| 最近记录: |