我想在C中按行(升序)排序我的矩阵

时间:2014-12-20 19:10:35

标签: c matrix

我想按升序重新排序我的矩阵,但它应该按行排序,我有点卡住并遇到麻烦。这就是它的样子。

离。

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();
}

2 个答案:

答案 0 :(得分:0)

这里的排序技术如下:

假设|之前的所有元素都已排序

|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();
}

答案 1 :(得分:0)

根本不确定我是否了解了所有内容,但是:

void sort_int_tab(int * tab,unsigned int size)

{

unsigned int        i;
unsigned int        j;
int            tmp;

i = 0;
while (i < size)
{
    j = 0;
    while (j < size - 1)
    {
        if (tab[j] > tab[j + 1])
        {
            tmp = tab[j];
            tab[j] = tab[j + 1];
            tab[j + 1] = tmp;
        }
        j++;
    }
    i++;
}

}

int i = 0;

while(i&lt; n)

{

sort_int_tab(arr[i], n);
i++;

}