find the max value of each column of a 2d array - c

#i want to find the max value of each row, i already created an array in the main of size[5][2], and i want to find the max value for each column#
void
maximum(int a[5][2])
{
int max = a[0][0];
int i, j;
for (i = 0; i < 2; i++) {
int max = a[0][i];
for (j = 0; j < 5; j++)
if (a[j][i] > max)
max = a[j][i];
}
printf("Maximum of 1st column= %d \n", max);
for (i = 0; i < 2; i++) {
int max = a[1][i];
for (j = 0; j < 5; j++)
if (a[j][i] > max)
max = a[j][i];
}
printf("Maximum of 2st column= %d \n", max);
max = a[0][0];
for (i = 0; i < 2; i++) {
for (j = 0; j < 5; j++) {
if (a[i][j] > max)
max = a[i][j];
}
}
printf("Maximum of all %d \n", max);
}

You're doing it the opposite way. [0][i] is the first row, not the first column. You must do it like [i][0] and [i][1], and same for the j. It's max=a[i][j].
Doing like like you say only checks the max of the first and second row, leaving the other three unchecked. Hope it helps.

You need to choose carefully the indeces and their order.
#include <stdio.h>
#include <stdlib.h>
void show_max(int rows, int cols, int mat[rows][cols])
{ // ^^^^ ^^^^ ^^^^^^^^^^^^^^^ VLA notation
// Traverse the array row-major order
for (int r = 0; r < rows; ++r)
{
int max = mat[r][0];
// ^^^^ First element of row r
for (int c = 1; c < cols; ++c)
{
if (mat[r][c] > max)
max = mat[r][c];
// ^^^^
}
printf("Max of ROW %d: %d\n", r, max);
}
int max_global = mat[0][0];
// Traverse the array in colmun-major order
for (int c = 0; c < cols; ++c) // <--
{
int max = mat[0][c];
// ^^^^ // First element of column c
for (int r = 1; r < rows; ++r) // <--
{
if (mat[r][c] > max)
max = mat[r][c];
// ^^^^
}
printf("Max of COLUMN %d: %d\n", c, max);
// This could be in the first nested loop.
if (max > max_global)
max_global = max;
}
printf("Max ELEMENT: %d\n", max_global);
}
int main(void)
{
int mat[5][2] = {{1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10}};
show_max(5, 2, mat);
}

Related

Sorting a matrix

Im trying to sort a matrix by the sum of its row's digits, from highest to lowest. I dont know if i explained that correctly so here's some photos explaining it.
This is what my code outputs. Basically, it asks you for m and n, which are the dimensions of the matrix. In this example it's a 3x4, 3 rows and 4 columns. Then, the matrix should be sorted by rows, by the sum of row's digits. Which means, instead of what's being outputted in the picture above, the correct result should be this:
I have no idea how to sort this from highest to lowest, i have been trying for hours to no avail.
Here's my code:
#include <stdio.h>
#define N 30
void main(){
double a[N][N], s[N], p;
int i, j, m, n, max;
while(1){
printf("\nm, n? ");
scanf("%d%d", &m, &n);
if(m <= 0 || m > N || n <=0 || n > N)
break;
for(i = 0; i < m; i++){
printf("%2d. row? ", i+1);
for(j = 0; j < n; scanf("%lf", &a[i][j++]));
}
for(i = 0; i < m; i++)
for(s[i] = j = 0; j < n; s[i] += a[i][j++]);
for(j = 0; j < n - 1; j++){
for(max = i, j = i+1; j < n; j++)
if(s[j] > s[max])
max = i;
if(max != j){
p = s[j];
s[j] = s[max];
s[max] = p;
for(j = 0; j < m; j++){
p = a[j][i];
a[j][i] = a[j][max];
a[j][max] = p;
}
}
}
printf("New matrix: \n");
for(i = 0; i < m; i++){
for(j = 0; j < n; printf("%8.2lf", a[i][j++]));
printf("\n");
}
for(j = 0; j < m; j++)
printf("-------------");
printf("\n");
for(j = 0; j < m; printf("%8.2f \n", s[j++]));
printf("\n");
}
}
You can sort the rows of the matrix from highest to lowest, using a simple bubble sort algorithm.Your code modified below:
int main() {
double a[N][N], s[N], p;
int i, j, m, n, max;
while (1) {
printf("\nm, n? ");
scanf("%d%d", & m, & n);
if (m <= 0 || m > N || n <= 0 || n > N)
break;
for (i = 0; i < m; i++) {
printf("%2d. row? ", i + 1);
for (j = 0; j < n; scanf("%lf", & a[i][j++]));
}
for (i = 0; i < m; i++)
for (s[i] = j = 0; j < n; s[i] += a[i][j++]);
for (i = 0; i < m - 1; i++) { // modified here
for (j = i + 1; j < m; j++) { // modified here
if (s[j] > s[i]) { // modified here
p = s[i];
s[i] = s[j];
s[j] = p;
for (int k = 0; k < n; k++) {
p = a[i][k];
a[i][k] = a[j][k];
a[j][k] = p;
}
}
}
}
printf("New matrix: \n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; printf("%8.2lf", a[i][j++]));
printf("\n");
}
for (j = 0; j < m; j++)
printf("-------------");
printf("\n");
for (j = 0; j < m; printf("%8.2f \n", s[j++]));
printf("\n");
}
return 0;
}
Here's how i modified your code to achieve that:
Initialize a loop variable i to 0.
In the outer loop, run the inner loop j from i+1 to m-1.
In the inner loop, compare the sum of the row i with the sum of row
j. If the sum of row j is greater than the sum of row i, swap the
rows using a temporary variable.
After the inner loop finishes, increment the value of i by 1. Repeat
the outer loop until i becomes equal to m-1.
Output:
You can just use qsort to let it handle the sorting and item swapping. Then you only need to write the code for comparing two rows with each other.
Given something like this:
int matrix[3][4] =
{
{1,2,3,4},
{5,6,7,8},
{9,1,2,3},
};
You'd call qsort as:
qsort(matrix, 3, sizeof(int[4]), compare);
The only complexity is implementing the comparison callback function. There's two things to consider there:
We've told qsort that we have an array of 3 items, each of type int[4]. So the void pointers it passes along to us will actually be pointers to type int[4]. That is: int(*)[4].
qsort sorts in ascending order by default, where the item considered "less" ends up first. So we need to tweak that to get the largest item first.
Example:
int compare (const void* obj1, const void* obj2)
{
const int (*ptr1)[4] = obj1;
const int (*ptr2)[4] = obj2;
size_t sum1=0;
size_t sum2=0;
for(size_t i=0; i<4; i++)
{
sum1 += (*ptr1)[i];
sum2 += (*ptr2)[i];
}
if(sum1 > sum2) // largest sum considered "less" for qsort
return -1;
else
return 1;
return 0;
}
sum1 < sum2 would have placed the smallest row first.
Full example:
#include <stdio.h>
#include <stdlib.h>
int compare (const void* obj1, const void* obj2)
{
const int (*ptr1)[4] = obj1;
const int (*ptr2)[4] = obj2;
size_t sum1=0;
size_t sum2=0;
for(size_t i=0; i<4; i++)
{
sum1 += (*ptr1)[i];
sum2 += (*ptr2)[i];
}
if(sum1 > sum2) // largest sum considered "less" for qsort
return -1;
else
return 1;
return 0;
}
void print_matrix(size_t col, size_t row, int matrix[col][row])
{
for(size_t i=0; i<col; i++)
{
for(size_t j=0; j<row; j++)
{
printf("%d,", matrix[i][j]);
}
puts("");
}
}
int main (void)
{
int matrix[3][4] =
{
{1,2,3,4},
{5,6,7,8},
{9,1,2,3},
};
print_matrix(3,4,matrix);
puts("");
qsort(matrix, 3, sizeof(int[4]), compare);
print_matrix(3,4,matrix);
}

Matrix manipulation to find biggest elements in their row & column

Our teacher asks to manipulate and search through a 25x15 matrix to find the biggest elements in their own Row & Column: if the (i,j) element is bigger than the mean value of i row, and bigger than the mean value of j column, then we can increment the counter that we'll return from the given function. After we found all of these so-called "Important Points" we search in them for the biggest of all, and pass the value and its coordinates to the Main by using the pointers passed to the function to modify the original variables.
The core of the exercise is the function to implement, with the given arguments:
int Importants(int a[ROW][COL], int *mi, int *mj, int *max);
I preferred to use more little functions to call when needed, than to implement everything in a big block, so I created the functions to find the mean value of a given column and row, the biggest element in a row.
We tried to use a supplementary array to store the positions, to bypass the pointers requisite, which contains a triplet of (i,j coordinate + value); anyway I'm not sure it's the right way.
Here's the full source-code
/*
In a matrix, the (i,j) couple is considered "IMPORTANT" is its value is
Bigger Than the Mean Value of the i row && Bigger Than the Mean Value of the j column
The exercise is to create, aside from Create (in the given interval) and Print functions, a function
named "Importants" which returns the number of Important points of the matrix; then search in these points
which one is the biggest and returns its value and coordinates by using the pointers defined in the function call.
FUNCTION DEFINITION CAN NOT BE ALTERED
*/
//import libraries
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//constant defines
#define ROW 25
#define COL 15
#define MIN 3
#define MAX 47
//vector with (i,j) positions and their value: every 3 elements you have 'i' row number, 'j' column number, and 'k' or 'max' value
int positions[COL*3];
//matrix generation with no first row element equal to the previous and next one
void create_matrix(int mat[][COL]) {
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
//first generation try
mat[i][j] = rand() % (MAX - MIN + 1) + MIN;
//checks
if ((mat[i][j] == mat[i-1][j]) && (mat[i][j] == mat[i+1][j]) && (i >= 1)) {
if (j > 0){
j--;
continue;
}
else {
continue;
}
}
else if ((mat[i][j] == mat[i+1][j]) && i >= 1) {
if (j > 0){
j--;
}
else {
continue;
}
}
}
}
puts("Matrix Generated.\n\n");
}
//generate a vector with all zeros to avoid mistakes
void zero_vector(int vector[]) {
for (int i = 0; i < COL*3;i++) {
vector[i] = 0;
}
}
//print matrix
void print_matrix(int mat[][COL]) {
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
printf("[ %2i ] ", mat[i][j]);
}
printf("\n");
}
}
//find max element in a given row
int max_in_row(int mat[][COL], int i) {
int max_value = 0, second_max = 0;
for (int r = i, c = 0; c < COL; c++) {
if (mat[r][c] > max_value) {
second_max = max_value;
max_value = mat[r][c];
}
}
return max_value;
}
//find max element in Positions vector
void max_in_positions_vector(int vector[]) {
int max_value = 0, second_max_value = 0;
for (int i = 2; i < COL*3; i=i+3) {
if (vector[i] > max_value) {
second_max_value = max_value;
max_value = vector[i];
}
}
printf("\n\nThe biggest of \'Important Positions\' is:\t%i", max_value);
}
//calculate mean value of a given row
int row_mean_value(int mat[][COL], int i, int j) {
int r_mean = 0, sum = 0;
for (int r = i, c = j; c < COL; c++){
sum += mat[r][c];
}
r_mean = sum / COL;
printf("\nMean value of Row %i:\t%i", i, r_mean);
return r_mean;
}
//calculate mean value of a given column
int column_mean_value(int mat[][COL], int i, int j) {
int c_mean = 0, sum = 0;
for (int r = i, c = j; r < ROW; r++){
sum += mat[r][c];
}
c_mean = sum / ROW;
printf("\nmedia colonna %i:\t%i", i, c_mean);
return c_mean;
}
int Importants(int a[ROW][COL], int *mi, int *mj, int *max){
int i = 0, j = 0, n_Importants = 0, max_value, k;
for (i,k = 0; i < ROW; i++) {
max_value = max_in_row(a, i);
//row_mean_value(a,i,j);
for (j = 0; j < COL; j++) {
if (max_value > row_mean_value(a,i,j) && max_value > column_mean_value(a,i,j)){
n_Importants++;
positions[k] = i;
positions[k+1] = j;
positions[k+2] = max_value;
k += 3;
//debug prints
printf("\nMax Value n. %i:\t%i", j, max_value);
printf("\ni = %i\tj = %i\tk = %i\n\n", i, j, k);
}
}
}
return n_Importants;
}
//main function
int main() {
srand(time(NULL));
int mat[ROW][COL];
int mi = 0, mj = 0, max = 0, *mi_p = &mi, *mj_p = &mj, *max_p = &max;
create_matrix(mat);
print_matrix(mat);
zero_vector(positions);
int n_Importants = Importants(mat, mi_p, mj_p, max_p);
max_in_positions_vector(positions);
return 0;
}
I've updated the k cycle to iterate every k+3 as suggested only inside the if block; As noted, mi, mj are not used, and that's part of the problem and why I chose to use an array of positions: the "Importants" function definition can not be altered, and so I would have to use the variable pointers. Also I've edited the call to the max_in_vector function to the correct max_in_row function name.
Updates
I've worked on it, removed the positions array and used the pointers to pass back the coordinates, by implementing a search in the matrix from within the Importants function; I've adjusted the search because I think I have to check every element, else it would only check for the maximum of the row && column. I don't know how to explain it well, so I'll post the updated code:
//imports
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//global constants
#define ROW 25
#define COL 15
#define MIN 3
#define MAX 47
//int posizioni[COL*3];
int importants_vect[ROW*COL];
//create matrix with no duplicates for the first element of 2 adjacent rows (a[i][j] != a[i-1][j] AND a[i][j] != a[i+1][j])
void create_matrix(int mat[][COL]) {
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
mat[i][j] = rand() % (MAX - MIN + 1) + MIN;
if ((mat[i][j] == mat[i-1][j]) && (mat[i][j] == mat[i+1][j]) && (i >= 1)) {
if (j > 0){
j--;
continue;
}
else {
continue;
}
}
else if ((mat[i][j] == mat[i+1][j]) && i >= 1) {
if (j > 0){
j--;
}
else {
continue;
}
}
}
}
puts("Matrix Generated.\n\n");
}
void zero_vector_init(int vect[]) {
for (int i = 0; i < COL*3;i++) {
vect[i] = 0;
}
}
//print matrix function
void print_matrix(int mat[][COL]) {
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
printf("[ %2i ] ", mat[i][j]);
}
printf("\n");
}
}
/* void maxi_vect(int vect[]) {
int max_value = 0, second_max_value = 0;
for (int i = 2; i < COL*3; i=i+3) {
if (vect[i] > max_value) {
second_max_value = max_value;
max_value = vect[i];
}
}
printf("\n\nIl max_value tra i punti importants e':\t%i", max_value);
} */
//find the mean of a given row
int row_mean_value(int mat[][COL], int i, int j) {
int r_mean = 0, sum = 0;
for (int r = i, c = j; c < COL; c++){
sum += mat[r][c];
}
r_mean = sum / COL;
printf("\nrow mean = %i / %i >>> %i", sum, COL, r_mean);
return r_mean;
}
//find the mean value in a given column
int column_mean_value(int mat[][COL], int i, int j) {
int c_mean = 0, sum = 0, r = 0, c = j;
for (r = i; r < ROW; r++){
sum += mat[r][c];
}
c_mean = sum / ROW;
printf("\ncolumn mean = %i / %i >>> %i", sum, ROW, c_mean);
return c_mean;
}
int max_in_vector(int vect[]) {
int max_value = 0, second_max_value = 0;
for (int i = 0; i < ROW*COL; i++) {
if (vect[i] > max_value) {
second_max_value = max_value;
max_value = vect[i];
}
}
return max_value;
}
//search inside the matrix for a given value and communicate its coordinates by modifying pointers to variables
void search_in_matrix(int mat[][COL], int to_search, int *mi, int *mj) {
//row and col variables are used for completeness, else we could just work with pointers
int found = 0, found_row = 0, found_col = 0;
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
if (mat[i][j] == to_search) {
found = mat[i][j];
found_col = j;
found_row = i;
}
}
}
*mi = found_row;
*mj = found_col;
return;
}
int Importants(int a[ROW][COL], int *mi, int *mj, int *max){
//init variables, including the ones to modify coordinate pointers
int n_importants = 0, i_coord = 0, j_coord = 0, max_p = 0;
//init mean value variables
int r_mean = 0, c_mean = 0;
//init counters
int i = 0, j = 0, k = 0;
//traversing the matrix
for (i ; i < ROW; i++) {
//calculate the mean of the row we're in
r_mean = row_mean_value(a, i, j);
for (j , k; j < COL; j++, k++) {
//calculating the mean of the column we're in
c_mean = column_mean_value(a, i, j);
//check for Important Point: a[i][j] MUST BE STRICTLY GREATER than r_mean and c_mean
if (a[i][j] > r_mean && a[i][j] > c_mean) {
//increment n_importants counter and fill the supplementary array with the value
n_importants++;
importants_vect[k] = a[i][j];
}
else continue;
}
//reinit j to 0. There are problems in print if not. Still don't know why
j = 0;
}
//search for the max in the supplementary array then search for its coordinates in the matrix
//and pass them back to the coordinate pointers
max_p = max_in_vector(importants_vect);
search_in_matrix(a, max_p, mi, mj);
return n_importants;
}
int main() {
srand(time(NULL));
int mat[ROW][COL];
int mi = 0, mj = 0, max = 0;
create_matrix(mat);
print_matrix(mat);
//zero_vector_init(posizioni);
zero_vector_init(importants_vect);
int n_importants = Importants(mat, &mi, &mj, &max);
//maxi_vect(posizioni);
int max_value = max_in_vector(importants_vect);
//int search = search_in_matrix(mat, max_value);
printf("\n\nThere are %i Important Points inside the matrix", n_importants);
printf("\n\nThe max among Important Points is\t%i\n", max_value);
printf("It's found on the row n°\t%i\n", mi);
printf("And on column n°\t%i\n\n", mj);
//printf("media: %.2f", med);
return 0;
}

Finding the origin of a calculation before it got sorted?

I wanted to find the sum of each row and then sort it. I managed to do this but to make it more complicated I decided to find from which row the min sum and the max sum was originated.
Example: The row with the min sum is the 3rd and the row with the max sum is is the 5th.
The main issue in my approach that I attempted was that the b[] array (in the sortfunction below) which I used to store the initial sum of each row is now replaced with the sorted values and I cannot work with the unsorted values which would show the rows that are needed.
#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.
}
This prints:
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
and it needs to print also this:
The row with the min sum is in the 3rd row
The row with the max sum us un the 5th row.
One solution would be to make b an array of a struct with the sum and row numbers. The swap() and sortfunction() functions would then be as follows (including some minor simplifications):
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");
}
}
After sorting b with respect to the sum, the original row numbers are then available for each entry.

How do I selection sort array A to B without copying arrays?

#include <stdio.h>
int size;
void SelectionSort(int a[], int size) {
int i, j, t, min, b[] = { 0,0,0,0,0,0,0,0 };
printf("\nelements to sort : ");
for (t = 0; t < size; t++) printf("%d ", a[t]);
printf("\n\n<<<<<<<<<<<<<<<<< selection sort >>>>>>>>>>>>\n");
for (i = 0; i < size - 1; i++) {
min = i;
for (j = i + 1; j < size; j++) {
if (a[j] < a[min]) min = j;
}
b[i] = a[min];
printf("\nA ARRAY %d : ", i + 1);
for (t = 0; t < size; t++) printf("%3d", a[t]);
printf("\nB ARRAY %d : ", i + 1);
for (t = 0; t < size; t++) printf("%3d", b[t]);
}
}
void main() {
int list[8] = { 69, 10, 30, 2, 16, 8, 31, 22 };
size = 8;
SelectionSort(list, size);
getchar();
}
the issue is that whenever the comparing is done the number 2 is copied in the array
what should i do to fix this?
Each step of the selection sort needs to
Identify the least element in the subarray
Remove the element
Place it at the front
Your code is skipping step 2. So it keeps finding the 2 until i increments past it.
Instead of copying into a different array b, swap the lowest element with a[i].
t = a[min];
a[min] = a[i];
a[i] = t;
BTW, it would be helpful in this sort of question to show us the output so potential answerers don't need to compile and run the program themselves.
Here is a modification of the usual selection sort, that takes duplicates into account.
In each inner loop, the whole array is read. Only values larger than the preceding minimum (lmin) are considered, and values equal to the current accepted minimum (min) are counted (nmin is the count). Then, the array b is updated with nmin values equal to min. The first loop is a special case as there is no preceding minimum.
#include <stdio.h>
void selection_sort(int n, int a[n], int b[n]) {
int j, k, lmin, min, nmin, first;
min = a[0];
nmin = 1;
for (j = 1; j < n; j++) {
if (a[j] == min) {
nmin++;
} else if (a[j] < min) {
min = a[j];
nmin = 1;
}
}
for (k = 0; nmin > 0; nmin--) {
b[k++] = min;
}
while (k < n) {
lmin = min;
first = 1;
for (j = 0; j < n; j++) {
if (a[j] > lmin) {
if (first) {
first = 0;
min = a[j];
nmin = 1;
} else if (a[j] == min) {
nmin++;
} else if (a[j] < min) {
min = a[j];
nmin = 1;
}
}
}
for ( ; nmin > 0; nmin--) {
b[k++] = min;
}
}
}
#define N 20
int main(void) {
int a[] = {2, 5, 9, 8, 4, 7, 1, 7, 5, 0, 3, 8, 3, 3, 6, 1, 8, 0, 2, 8};
int b[N];
selection_sort(N, a, b);
for (int i = 0; i < N; i++) {
printf("%d ", a[i]);
}
printf("\n");
for (int i = 0; i < N; i++) {
printf("%d ", b[i]);
}
printf("\n");
return 0;
}
The purpose of the boolean first is to detect the first accepted current minimum (that is, the first value that is larger than lmin).
Another way would be to set min = INT_MAX before the beginning of the inner loop, where INT_MAX is the maximum int value (defined in limits.h): we know lmin < INT_MAX, otherwise we would already have exited the function. Here is this variant:
#include <stdio.h>
#include <limits.h>
void selection_sort(int n, int a[n], int b[n]) {
int j, k, lmin, min, nmin;
min = a[0];
nmin = 1;
for (j = 1; j < n; j++) {
if (a[j] == min) {
nmin++;
} else if (a[j] < min) {
min = a[j];
nmin = 1;
}
}
for (k = 0; nmin > 0; nmin--) {
b[k++] = min;
}
while (k < n) {
lmin = min;
min = INT_MAX;
nmin = 0;
for (j = 0; j < n; j++) {
if (a[j] > lmin) {
if (a[j] < min) {
min = a[j];
nmin = 1;
} else if (a[j] == min) {
nmin++;
}
}
}
for ( ; nmin > 0; nmin--) {
b[k++] = min;
}
}
}
#define N 20
int main(void) {
int a[] = {2, 5, 9, 8, 4, 7, 1, 7, 5, 0, 3, 8, 3, 3, 6, 1, 8, 0, 2, 8};
int b[N];
selection_sort(N, a, b);
for (int i = 0; i < N; i++) {
printf("%d ", a[i]);
}
printf("\n");
for (int i = 0; i < N; i++) {
printf("%d ", b[i]);
}
printf("\n");
return 0;
}
Note that in this version, nmin is set to zero before the inner loop: it doesn't matter if there are values smaller than INT_MAX. But if all remaining values are equal to INT_MAX, we are going to count them with nmin++, so we must start at zero.

2D array how to print a number and it's coordinates

I need to find and print out the max and min number in each row of a 2D array. This is what I have tried so far.
int max(int N, int masyvas[][])
{
int i, j, max[N][N]
for(i=0; i<N; i++)
for(j=i; j<N; j++)
if(masyvas[i][j] > max) max=masyvas[i][j];
return max;
}
I know this doesn't work, but is it any close to being at least useful? Any suggestions on how should I approach this?
You're very close. The two main problems are max type (it shouldn't be
another array, but just a normal int), and the fact that you didn't reset
your max value before each row.
int i, j, max;
for(i=0; i<N; i++) {
max = 0; // reset max before checking a row
for(j=i; j<N; j++) {
if (masyvas[i][j] > max) max = masyvas[i][j];
}
}
It shouldn't be difficult to add a min check too:
int i, j, max, min;
for(i=0; i<N; i++) {
max = min = 0; // reset max & min before checking a row
for(j=i; j<N; j++) {
if (masyvas[i][j] > max) max = masyvas[i][j];
if (masyvas[i][j] < min) min = masyvas[i][j];
}
// print the values here
}
Now, you say you want to print those values. You can do so at the end of the
outer loop, as marked above. Returning the final value like in your original
code doesn't make much sense since only the final row max and min would still
be there. Another approach, which might be what you intended though, is to
make max and min an array and return a pointer:
int *maxValues = calloc(sizeof(int) * N);
int i, j;
for(i=0; i<N; i++)
for(j=i; j<N; j++)
if (masyvas[i][j] > maxValues[i]) maxValues[i] = masyvas[i][j];
return maxValues;
You probably already noticed that to return both max and min values (arrays)
you will need another level of pointers...
int **
find_max_and_min(int **masyvas)
{
int **values = malloc(sizeof(int *) * 2);
values[0] = calloc(sizeof(int) * N); // to hold min
values[1] = calloc(sizeof(int) * N); // to hold max
for (int i = 0; i < N; i++) {
for (int j = i; j < N; j++) {
if (masyvas[i][j] > values[1][i]) values[1][i] = masyvas[i][j];
if (masyvas[i][j] < values[0][i]) values[0][i] = masyvas[i][j];
}
}
return values;
}
int **result = find_max_and_min(data);
// now result[0] is a 1d array of N size with the minimal values of each
// row i from data, and result[1] is a similar array but holding the max
// of each row.
my solution:
#include <stdio.h>
struct Output {
int value;
int pos;
};
void max(int N, int masyvas[N][N], struct Output max_by_rows[N]){
int i, j;
for(i=0; i<N; i++){
max_by_rows[i].value = masyvas[i][0];
max_by_rows[i].pos = 0;
for(j=i; j<N; j++)
if(masyvas[i][j] > max_by_rows[i].value)
{
max_by_rows[i].value=masyvas[i][j];
max_by_rows[i].pos = j;
}
}
}
void min(int N, int masyvas[N][N], struct Output min_by_rows[N]){
int i, j;
for(i=0; i<N; i++){
min_by_rows[i].value = masyvas[i][0];
min_by_rows[i].pos = 0;
for(j=i; j<N; j++)
if(masyvas[i][j] < min_by_rows[i].value)
{
min_by_rows[i].value=masyvas[i][j];
min_by_rows[i].pos = j;
}
}
}
int main(){
int N = 4;
int a[4][4] = {
{0, 1, 2, 3} ,
{7, 6, 5, 4} ,
{8, 9, 10, 11},
{15, 14, 13,12}
};
struct Output maxs[4];
struct Output mins[4];
max(N, a, maxs);
min(N, a, mins);
int i;
for(i=0; i <N; i++)
{
printf("row %d \tmax: %d\tpos: %d\tmin: %d\tpos: %d\n", i, maxs[i].value, maxs[i].pos, mins[i].value, mins[i].pos);
}
return 0;
}
output:
row 0 max: 3 pos: 3 min: 0 pos: 0
row 1 max: 7 pos: 0 min: 4 pos: 3
row 2 max: 11 pos: 3 min: 8 pos: 0
row 3 max: 15 pos: 0 min: 12 pos: 3
int i, j, max, min;
for(i=0; i<N; i++) {
max = 0;
min = 0;
for(j=i; j<N; j++ ) {
if (masyvas[i][j] > max)
max = masyvas[i][j];
if (masyvas[i][j] < min)
min = masyvas[i][j];
}
}

Resources