1. Write a C program to arrange row elements in ascending order using functions & dynamic memory allocation.
2. Write a C program to arrange column elements in ascending order using functions &
dynamic memory allocation.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct matrix {
int n, m;
int *val;
} Matrix;
Matrix* alloc_mat(int n, int m);
void free_mat(Matrix* mat);
int get_el(Matrix* mat, int i, int j);
void set_el(Matrix* mat, int i, int j, int x);
void rand_mat(Matrix* mat, int imin, int imax);
void print_mat(Matrix* mat);
void sort_row(Matrix* mat);
void sort_col(Matrix* mat);
int main()
{
Matrix* m;
srand(time(NULL));
m = alloc_mat(3, 4);
rand_mat(m, 1, 10);
printf("Original matrix:\n");
print_mat(m);
printf("\nSorted by row:\n");
sort_row(m);
print_mat(m);
printf("\nSorted by column:\n");
sort_col(m);
print_mat(m);
free_mat(m);
return 0;
}
int get_el(Matrix* m, int i, int j) {
if (i<0 || i>= m->n) {
printf("Error row index %d out of range (%d)\n", i, m->n);
exit(1);
}
if (j<0 || j>=m->m) {
printf("Error col index %d out of range (%d)\n", j, m->m);
exit(1);
}
return m->val[i*m->m + j];
}
void set_el(Matrix* m, int i, int j, int x) {
if (i<0 || i>= m->n) {
printf("Error row index %d out of range (%d)\n", i, m->n);
exit(1);
}
if (j<0 || j>=m->m) {
printf("Error col index %d out of range (%d)\n", j, m->m);
exit(1);
}
m->val[i*m->m + j] = x;
}
Matrix* alloc_mat(int n, int m) {
Matrix* mat = (Matrix*) malloc(sizeof(struct matrix));
mat->n = n;
mat->m = m;
mat->val = (int *) malloc(sizeof(int)*m*n);
return mat;
}
void free_mat(Matrix* mat) {
free(mat->val);
free(mat);
}
void rand_mat(Matrix* mat, int imin, int imax) {
int i, j, x;
for (i=0; i<mat->n; i++) {
for (j=0; j<mat->m; j++) {
x = rand() % (imax - imin) + imin;
set_el(mat, i, j, x);
}
}
}
void print_mat(Matrix* mat) {
int i, j;
for (i=0; i<mat->n; i++) {
printf("[");
for (j=0; j<mat->m-1; j++) {
printf("%d, ", get_el(mat, i, j));
}
printf("%d ]\n", get_el(mat, i, mat->m-1));
}
}
void sort_row(Matrix* mat) {
int i, j, k, k_min, x;
for (i=0; i<mat->n; i++) {
for (j=0; j<mat->m-1; j++) {
k_min = j;
for (k=j+1; k<mat->m; k++) {
if (get_el(mat, i, k) < get_el(mat, i, k_min)) {
k_min = k;
}
}
if (k_min != j) {
x = get_el(mat, i, j);
set_el(mat, i, j, get_el(mat, i, k_min));
set_el(mat, i, k_min, x);
}
}
}
}
void sort_col(Matrix* mat) {
int i, j, k, k_min, x;
for (j=0; j<mat->m; j++) {
for (i=0; i<mat->n-1; i++) {
k_min = i;
for (k=i+1; k<mat->n; k++) {
if (get_el(mat, k, j) < get_el(mat, k_min, j)) {
k_min = k;
}
}
if (k_min != i) {
x = get_el(mat, i, j);
set_el(mat, i, j, get_el(mat, k_min, j));
set_el(mat, k_min, j, x);
}
}
}
}
Comments
Thanks a lot !!
Leave a comment