I know how to find it with the help of an additional array and sorting, but I need another implementation.

    2 answers 2

    Algorithm:

    1. Initialize a and b with a value equal to the largest possible integer.
    2. Sequentially go through all the elements of the matrix in any order.
    3. If the current element is less than a , then update a and b .
    4. Otherwise, if the current element is less than b , update b .
    5. Print a and b .

    The complexity is O (n).

      And something in this spirit will not work? It is trivial to not care about the multidimensionality of an array and walk along it linearly.

      m1 := 0; m2 := 0; { 0 — специальное значение, означающее «еще не нашли» } for i := 1 to 3 do for j := 1 to 3 do if m[i, j] > 0 then { Или если мы еще не нашли ни одного положительного числа (m1 <= 0), или если текущее значение меньше самого малого (m1) } if m1 <= 0 or m[i, j] < m1 then m1 := m[i, j] { Если мы не нашли второго положительного числа (m2 <= 0), или если текущее значение больше либо равно m1, но меньше второго по порядку наименьшего (m2) } else if m2 <= 0 or m[i, j] < m2 then m2 := m[i, j]; 

      For simplicity, I do not remember the indexes. If there are not enough positive numbers, m2 (and possibly m1 ) will be zero. If there are two identical smallest ones, the m1 branch will work on one, m1 will be no less on the other, and m2 work.

      The code was written on the knee, without testing, possible typos.