Question

Analysis of algorithms. C++ pseudo code please

Analysis of algorithms. C++ pseudo code please
media%2Fa9a%2Fa9a1113d-dcbd-41c8-954b-87
0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include <iostream>
using namespace std;

int main ()
{
// N*M (5 * 8)
int matrix [5][8] = {
{10, 20, 30, 40, 50, 60, 70, 80},
{9, 19, 25, 39, 49, 55, 66, 79},
{7, 15, 23, 37, 45, 53, 65, 77},
{5, 13, 22, 35, 44, 52, 64, 75},
{4, 12, 21, 31, 43, 51, 63, 73}
};
  
// Size of matrix
int N=5, M=8;
  
// Key we need to find
int KEY = 71;
  
/*
* We First search our key in columns of first row and store that column in col,
* using this we can easily find column which can have our key.
* Here we are keeping row static (i.e first row) and search columns
*/
int col = -1;
int row = -1;
for ( int i=0 ; i < M ; i++ ) {
// As we are traversing column of first row,
//hence we took value of row 0 i.e first row
cout << matrix[0][i];
if(matrix[0][i] >= KEY) {
col = i;
break;
}
}
  
// if col is still -1 means we do not get any column having value less than KEY
if(col > -1) {
/* Now whatever column we get we search our key in that.
* Here we are keeping column static and search through rows.
*/
  
for ( int i=0 ; i < N ; i++ ) {
  
if(matrix[col][i] == KEY) {
row = i;
break;
}
}
  
}
  
if(col > -1 && row > -1) {
cout << "Element found at N: " << row+1 << " and M: " << col+1;
} else {
cout << "No Element found.";
}
  
return 0;
}

Illustration:

To find 71, We first start searching columns of first row and reach last row which gives us complexity of M as there are M columns. As we met our condition at last column the we came to know the element can only be present in this particular column. So we start traversing that particular column of each row and found no such key, here complexity is N as we traverse N rows. This is worst case as we need to traverse every column of first row and every row for that column.

Add a comment
Know the answer?
Add Answer to:
Analysis of algorithms. C++ pseudo code please
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT