我想按升序重新排列我的矩阵,但它应该是按行排列的,我有点卡住了,有点麻烦。这是它的样子。
前任。

3 5 4
9 2 8
6 4 8

应该是;
3 4 5
2 8 9
4 6 8

但是用我的代码把所有的东西都按升序排列!
2 3 4
4 5 6
8 8 9

这是我的完整代码:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

#define n 3

int main()
{
    int arr[n][n],min,i,j,tmp,y,k,w,z=0,q=0;
    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
        {
            printf("Enter number: ");
            scanf("%d",&arr[i][j]);
        }

    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
        {
            z = i;
            q = j;

            min = arr[i][j];
            w = j;

        for (k = i; k < n; k++)
        {
         for (; w < n; w++)
           if (arr[k][w] < min)
           {
            min = arr[k][w];
            z = k;
            q = w;
           }
         w = 0;
        }
       tmp=arr[i][j];
       arr[i][j]=min;
       arr[z][q]=tmp;
     }

    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
            printf("%d ",arr[i][j]);
        printf("\n");
    }
    getch();
}

最佳答案

这里的排序技术如下:
假设|排序之前的所有元素

|5 4 1 2

select 1st lowest value and insert it in 1st position

1 |4 5 2

select 2nd lowest value and insert it in 2nd position

1 2| 5 4

select 3rd lowest value and insert it in 3rd position

1 2 4| 5

select 4th lowest value and insert it in 4th position

1 2 4 5| ...no elements left :) Sorted order

因此,实施将是:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

#define n 3

int main()
{
    int arr[n][n],min,i,j,tmp,y,k,w,z=0,q=0;
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            printf("Enter number: ");
            scanf("%d",&arr[i][j]);
        }
    }

    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            z = j; // assuming that current value is j'th minimum

            min = arr[i][j];
            // Checking the j'th min value of i'th row
            for (k = j +1 ; k < n; k++)
            {
                if (arr[i][k] < min)
                {
                    min = arr[i][k];
                    z = k; // saving j'th min value
                }
            }
            // swapping current value with the j'th min value
            tmp=arr[i][j];
            arr[i][j]=min;
            arr[i][z]=tmp;
        }
    }

    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
            printf("%d ",arr[i][j]);
        printf("\n");
    }
    getch();
}

关于c - 我想在C中以行为基础(升序)对矩阵排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27583437/

10-08 21:02