сортировка матрицы с использованием сортировки по столбцам - PullRequest
0 голосов
/ 05 апреля 2020

в соответствии с книгой "Введение в алгоритмы" я попытался отсортировать матрицу с помощью столбца sort.The мой подход

1) сортировать каждую строку матрицы -

#include<stdio.h>
#include<stdlib.h>

void sort(int arr[3][3], int k)// here k defines  the column number ,k remains constant through out the function
                                  //because we have to sort the matrix column wise respectively
{
    int i;
    int c[10]={0};
    int b[3][3];
    for(i=0;i<3;i++)
    { c[arr[i][k]]++;
    }
    for(i=1;i<3;i++)
    {
        c[i]+=c[i-1];
    }
    for(i=2;i>=0;i--)
    {
        b[c[arr[i][k]]-1][k]=arr[i][k];
        c[arr[i][k]]--;
    }
    for(i=0;i<3;i++)
    {
        arr[i][k]=b[i][k];
    }
}

Я прошел k в качестве аргумента, который является номером столбца (так как он остается постоянным на протяжении сортировки каждого столбца, и изменяется только номер строки, поэтому я повторял только по номеру строки)

функция для передачи номер нужного столбца, который затем вызывает функцию счета

  void column(int arr[3][3]) // to call the function column wise by passing k as a parameter to count function
{
    int k;
    for(k=0;k<3;k++)
        sort(arr,k);
}

2) транспонировать матрицу

{
    int i,j,temp;
    for(i=0;i<3;i++)
    {   for(j=0;j<3;j++)
             temp=arr[i][j];
             arr[i][j]=arr[j][i];
             arr[j][i]=temp;
    }
}

функцию печати

   void print(int arr[3][3]) // to print the output
{
     int i,j;
    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
            {
                printf("%d ",arr[i][j]);
            }
             printf("\n");
    }
}

основная функция

{
    int arr[3][3];
    int i,j;
    for (i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
           scanf("%d ",&arr[i][j]);
    }
    // prints the array just inputed
    print(arr);
    // column calls the function sort according to the column
    column(arr);
    transpose(arr);  // matrix is transposed
    printf("\n");
    print(arr);      // matrix is printed
    column(arr);     // matrix is again passed with respect to the columns and sorted
    transpose(arr);   // matrix is transposed to get the original matrix
    printf("\n");
    print(arr);     //final result is printed
    return 0;
}

вывод маловероятен, как его правильно отсортировать

1 Ответ

0 голосов
/ 05 апреля 2020

Вот рабочая версия вашего кода. Я установил опущенную скобку и функцию транспонирования:

#include <stdio.h>
#include<stdlib.h>

void sort(int arr[3][3], int k)// here k defines  the column number ,k remains constant through out the function
                                  //because we have to sort the matrix column wise respectively
{
    int i,j;
    int tmp = 0;
    for(i=0;i<2;i++)
    { 
        for (j = 0; j < 3-i-1; j++) 
        {
           if (arr[j][k] > arr[j+1][k]) 
           {
              tmp = arr[j][k];
              arr[j][k] = arr[j+1][k];
              arr[j+1][k] = tmp;
           }
        }
    }
    printf("\n");
}

void column(int arr[3][3]) // to call the function column wise by passing k as a parameter to count function
{
    int k;
    for(k=0;k<3;k++)
    {
        sort(arr,k);
    }
}

void transpose(int arr[3][3])
{
    int i,j,temp;
    for(i=0;i<3;i++)
    {   
        for(j=0;j<3;j++)
        {
            if(i != j && i<j)
            {
                 temp=arr[i][j];
                 arr[i][j]=arr[j][i];
                 arr[j][i]=temp;
            }
        }
    }
}

void print(int arr[3][3]) // to print the output
{
     int i,j;
    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
            {
                printf("%d ",arr[i][j]);
            }
             printf("\n");
    }
}

int main()
{
    int arr[3][3] = {0};
    int i,j;
    for (i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
           scanf("%d ",&arr[i][j]);
    }
    printf("\n");
    // prints the array just inputed
    print(arr);
    printf("\n");
    // column calls the function sort according to the column
    column(arr);
    print(arr);
    transpose(arr);  // matrix is transposed
    printf("\n");
    print(arr);      // matrix is printed
    column(arr);     // matrix is again passed with respect to the columns and sorted
    printf("\n");
    print(arr);      // matrix is printed
    transpose(arr);   // matrix is transposed to get the original matrix
    printf("\n");
    print(arr);     //final result is printed
    return 0;
}

Вот результат: Sort, Transpose, Sort, затем транспонировать:

Sort Output

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...