在c中对2维数组进行排序

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

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 

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

 int x,y,z,j,temp1,temp2,temp3; for(x=0;x<i;x++) { for (j=0;ja[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; } } } 

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

看起来您正在尝试按字典顺序对数组的行进行排序。 如果将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); 

希望这可以帮助!

在c中排序2D数组

 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<