matrix into 1d array

i have this program i need to write it is supposed to extract 6 min numbers from matrix 4x4 and put them into 1d array. i'v written this code but it only finds 1 min element, i dont know how to find next 5 min elements, any help would be appreciated

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include<iostream>

using namespace std;

int main(){
    int array[4][4];
    int arrayOut[6];
    int min,num=0;
    
    cout<<"Enter elements of matrix "<<endl;
    for(int i=0;i<4;i++){
    for(int x=0;x<4;x++){
            cin>>array[i][x];
            }
            }
        
           
   min=array[0][0];
   for(int i=0;i<4;i++){
   for(int j=0;j<4;j++){
   if (array[i][j]<min){
   min=array[i][j];
  
 
  
    }}}
      arrayOut[broj]=min;
   
     cout<<arrayOut[num++]<<endl;
    
     
            
    system("pause");
    return 0;
    
    }

Easiest way? Keep they "arrayOut" sorted, check each element of array[i][j] to the "worst" minima, copy if better, then swap into position.

1
2
3
4
5
6
if (array[i][j] < minima[5]) {
    // Overwrite previous "6th minimum" as it is now nr 7 and doesn't have to be remembered.
    minima[5] = array[i][j];
    // Swap-walk it into position 't' so that minima[t-1] <= minima[t] <= minima[t+1].
    while (t > 0 && minima[t] < minima[t-1]) std::swap(minima[t], minima[t-1]);
}

The easiest way would be copying all values to a 1d array. Sort that 1d array and voila... the first 6 elements are what you want
Topic archived. No new replies allowed.