我想找到每一行的總和,然后對其進行排序。我設法做到了這一點,但為了讓它更復雜,我決定找出 themin sum和 themax sum的起源。
示例:帶有 的行min sum是第 3 行,帶有max sumis 的行是第 5 行。
我嘗試的方法中的主要問題是,sortfunction我用來存盤sum每行初始值的 b[] 陣列(在下面)現在被排序值替換,我無法使用未排序的值,這將顯示需要的行。
#include<stdio.h>
#define ROWS 5
#define COLS 3
void printnumbers(int arr[][COLS]);
void sortfunction(int arr[][COLS]);
int main() {
int arr[ROWS][COLS] = {{1, 2, 3},
{2, 3, 4},
{3, 1, 1},
{5, 5, 6},
{35, 335, 6}};
printnumbers(arr);
sortfunction(arr);
return 0;
}
void printnumbers(int arr[][COLS]){
int i,j;
for(i = 0; i<ROWS; i )
{
printf("\n");
for(j = 0; j<COLS; j )
{
printf("%d\t", arr[i][j]);
}
}
}
//swap function below
void swap(int* xp, int* yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// sort function
void sortfunction(int arr[][COLS]) {
int i, j, total, k, b[ROWS];
k = 0;
printf("\n");
for (i = 0; i < ROWS; i ) {
total = 0;
for (j = 0; j < COLS; j ) {
total = arr[i][j];
}
if (j == COLS) {
b[k] = total;
k = 1;
}
}
for (k = 0; k < ROWS; k ) {
printf("the sum of the %dst row is %d\n", k 1, b[k]);
}
int a, q, min_idx;
int n = sizeof(b) / sizeof(b[0]);
// One by one move boundary of unsorted subarray
for (q = 0; q < n - 1; q ) {
// Find the minimum element in unsorted array
min_idx = q;
for (a = q 1; a < n; a )
if (b[a] < b[min_idx])
min_idx = a;
// Swap the found minimum element
// with the first element
swap(&b[min_idx], &b[q]);
}
for (i = 0; i < n; i )
printf("%d ", b[i]);
printf("\n");
//Now I want to find which row has the least sum and which has the max sum but the b[] array is already sorted.
}
這列印:
the sum of the 1st row is 6
the sum of the 2st row is 9
the sum of the 3st row is 5
the sum of the 4st row is 16
the sum of the 5st row is 376
5 6 9 16 376 //it got sorted
它還需要列印這個:
The row with the min sum is in the 3rd row
The row with the max sum us un the 5th row.
uj5u.com熱心網友回復:
一種解決方案是b使用總和和行號創建一個結構陣列。然后swap(), andsortfunction()函式如下(包括一些小的簡化):
typedef struct
{
int sum;
int row;
} tRowSum;
//swap function below
void swap(tRowSum* xp, tRowSum* yp)
{
tRowSum temp = *xp;
*xp = *yp;
*yp = temp;
}
// sort function
void sortfunction(int arr[][COLS]) {
int i, j, total;
tRowSum b[ROWS];
printf("\n");
for (i = 0; i < ROWS; i ) {
total = 0;
for (j = 0; j < COLS; j ) {
total = arr[i][j];
}
b[i].sum = total;
b[i].row = i;
}
for (i = 0; i < ROWS; i ) {
printf("the sum of the %dst row is %d\n", i 1, b[i].sum);
}
int a, q, min_idx;
// One by one move boundary of unsorted subarray
for (q = 0; q < ROWS - 1; q ) {
// Find the minimum element in unsorted array
min_idx = q;
for (a = q 1; a < ROWS; a )
if (b[a].sum < b[min_idx].sum)
min_idx = a;
// Swap the found minimum element
// with the first element
swap(&b[min_idx], &b[q]);
}
for (i = 0; i < ROWS; i ) {
printf("%d (%d)", b[i].sum, b[i].row);
printf("\n");
}
}
在對總和進行排序后b,原始行號可用于每個條目。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/432747.html
