C/C++

Найти 10 максимальных элементов в матрице

Дана матрица А(5,5). Найти 10 максимальных элементов и переписать их в другой массив в обратном порядке.
Нужен код C++
* Konstantin *
* Konstantin *
91
#include <random>
#include <iostream>
#include <iomanip>
using namespace std;
int* min_element(int* box, const size_t n) {
auto min = box;
auto beg = box;
auto end = box + n;
while (++beg < end) if (*beg < *min) min = beg;
return min;
}
int* find_less(int value, int* box, const size_t n) {
auto min = min_element(box, n);
return value > *min ? min : box + n;
}
void replace(int value, int* pos, int* box, const size_t n) {
if (pos == box) *box = value;
else {
for (auto it = pos - 1; it >= box; --it, --pos) *pos = *it;
*box = value;
}
}
int main() {
uniform_int_distribution<> uid(100, 999);
mt19937 gen{ random_device()() };
const size_t n = 5;
int matrix[n][n];
for (auto& row : matrix) {
for (auto& value : row) {
value = uid(gen);
cout << setw(5) << value;
}
puts("\n");
}
const size_t m = n << 1;
auto j = m;
int box[m];
for (size_t i = 0; i < n; ++i) {
for (size_t k = 0; k < n; ++k) {
if (--j < m) box[j] = matrix[i][k];
else {
auto next = find_less(matrix[i][k], box, m);
if (next != box + m) replace(matrix[i][k], next, box, m);
}
}
}
puts("");
for (size_t i = 0; i < m; ++i) cout << setw(5) << box[i];
puts("");
}
ЛЯ
Леонид Ячменёв
51 467
Лучший ответ
#include <iostream>
#include <ctime>

using namespace std;

int main()
{
const int size1 = 5, size2 = 10;
int A[size1][size1],B[size2];
srand(time(nullptr));
rand();
for(int x = 0; x < size1; x++)
{
for(int y = 0; y < size1; y++)
{
A[x][y] = rand() % 20 + 1;
cout << A[x][y] << '\t';
}
cout << endl;
}
cout << endl;

for(int x = 0; x < size2; x++)
B[x] = 0; // начальное значение должно быть меньше любого из массива A

int tmp;
for(int x = 0; x < size1; x++)
{
for(int y = 0; y < size1; y++)
{
if(A[x][y] > B[0])
{
B[0] = A[x][y];
for(int z = 1; z < size2; z++)
{
if(B[z-1] > B[z])
{
tmp = B[z-1];
B[z-1] = B[z];
B[z] = tmp;
}
}
}
}
}

for(int x = 0; x < size2; x++)
cout << B[x] << ' ';
cout << endl;

return 0;
}
Dostonbek Rustamov
Dostonbek Rustamov
83 997

Похожие вопросы