在C语言中,对二维数组进行排序通常有以下几种方法:
按行排序
将二维数组转换为一维数组,然后使用排序算法(如冒泡排序、快速排序等)对一维数组进行排序。
示例代码(冒泡排序):
```c
include void bubble_sort(int arr[], int n) { for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } int main() { int matrix[] = {{5, 2, 8}, {1, 6, 3}, {7, 4, 9}}; int rows = sizeof(matrix) / sizeof(matrix); int cols = sizeof(matrix) / sizeof(matrix); // 将二维数组转换为一维数组 int one_dimensional[rows * cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { one_dimensional[i * cols + j] = matrix[i][j]; } } // 对一维数组进行排序 bubble_sort(one_dimensional, rows * cols); // 将排序后的一维数组转换回二维数组 for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { matrix[i][j] = one_dimensional[i * cols + j]; } } // 输出排序后的二维数组 for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("%d ", matrix[i][j]); } printf("\n"); } return 0; } ``` 可以将每一列的逻辑上当成一维数组进行排序,然后逐行更新。 示例代码(冒泡排序): ```c include void bubble_sort_column(int arr[], int rows, int cols, int col) { for (int i = 0; i < rows - 1; i++) { for (int j = 0; j < cols - 1; j++) { if (arr[i][j] > arr[i][j + 1]) { int temp = arr[i][j]; arr[i][j] = arr[i][j + 1]; arr[i][j + 1] = temp; } } } } int main() { int matrix[] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; int rows = sizeof(matrix) / sizeof(matrix); int cols = sizeof(matrix) / sizeof(matrix); // 对每一列进行排序 for (int col = 0; col < cols; col++) { bubble_sort_column(matrix, rows, cols, col); } // 输出排序后的二维数组 for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("%d ", matrix[i][j]); } printf("\n"); } return 0; } ``` 可以使用C标准库中的`qsort`函数对二维数组的每一行进行排序。 示例代码:按列排序
使用标准库函数