एक स्पार्स मैट्रिक्स वह मैट्रिक्स है जिसमें अधिकांश तत्व 0 होते हैं। एक उदाहरण निम्नानुसार दिया गया है।
नीचे दी गई मैट्रिक्स में 5 शून्य हैं। चूंकि शून्यों की संख्या मैट्रिक्स के तत्वों के आधे से अधिक है, यह एक स्पार्स मैट्रिक्स है।
0 0 9 5 0 8 7 0 0
एल्गोरिदम
Begin
a[10][10] को इंटीजर डेटाटाइप के 2D ऐरे के रूप में घोषित करें
ऐरे के कुछ मान इनिशियलाइज़ करें
i, j, count को इंटीजर डेटाटाइप के रूप में घोषित करें
count = 0 इनिशियलाइज़ करें
row, col को इंटीजर डेटाटाइप के रूप में घोषित करें
row = 3, col = 3 इनिशियलाइज़ करें
for (i = 0; i < row; ++i) {
for (j = 0; j < col; ++j)
if (a[i][j] == 0)
count++
"The matrix is:" प्रिंट करें
for (i = 0; i < row; ++i)
for (j = 0; j < col; ++j)
ऐरे के मान प्रिंट करें
"The number of zeros in the matrix are" प्रिंट करें
if (count > ((row * col) / 2)) then
"This is a sparse matrix" प्रिंट करें
else
"This is not a sparse matrix" प्रिंट करें
End
उदाहरण
#include <iostream>
using namespace std;
int main() {
int a[10][10] = { {0, 0, 9}, {5, 0, 8}, {7, 0, 0} };
int i, j, count = 0;
int row = 3, col = 3;
for (i = 0; i < row; ++i) {
for (j = 0; j < col; ++j) {
if (a[i][j] == 0)
count++;
}
}
cout << "The matrix is:" << endl;
for (i = 0; i < row; ++i) {
for (j = 0; j < col; ++j) {
cout << a[i][j] << " ";
}
cout << endl;
}
cout << "The number of zeros in the matrix are " << count << endl;
if (count > ((row * col) / 2))
cout << "This is a sparse matrix" << endl;
else
cout << "This is not a sparse matrix" << endl;
return 0;
}
आउटपुट
The matrix is: 0 0 9 5 0 8 7 0 0 The number of zeros in the matrix are 5 This is a sparse matrix