Hey all, newbie programmer here and looking for some help.

I have to search for the 3 smallest integers and 3 largest in my 3x3x3 array.

I have it loaded with random numbers already. However, I am not allowed to use any kind of sorting, (bubble, insertion).

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{  int test=0;
    int fun[3][3][3];
    int num=rand()%10;

    for(int i=0; i<3; i++)
    {
        for(int j=0; j<3; j++)
        {
            for(int k=0; k<3; k++)
            {
                fun[i][j][k]=rand()%10;
            }
        }
    }

    for(int i=0; i<3; i++)
    {    
        for(int j=0; j<3; j++)
        {    
            cout << " ";
            for(int k=0; k<3; k++)
            {    
                cout << fun[i][j][k] << " ";    
            }
        }
        cout << endl;
    }

How would you solve if it you were doing it by hand? A basic process might go something like this:

- Keep a set of 3 markers for each of high and low.
- Go over the array(s), and at each new value:
  - Determine if the new value fits in the set of lowest or highest
    - If it does, replace the one that gets bumped with the new value

Once you've traversed the array(s) once, you'll have your answer. ;)

You may want to consider how to treat duplicate values (i.e. can duplicates be stored more than once in the result lists or should you find unique low/high values).

Hmm i see what you're saying. But im having difficulty programming it. Im thinking while it loops through the array, to have an if statement checking to see if its a low or high value. That doesnt seem to be the best way to do it nor do i think its feasable without a bunch of if...else statements

Determining if it's the best depends on how you measure. Since it only reads the array once, my solution is very close to, if not, optimal in terms of performance. Using lots of if-else is not necessarily a bad thing compared to the tradeoff of, say, reading the whole array for each value you need in the result.

Though it might be a little more difficult, you could try keeping the small and large sublists (of 3 values) sorted, so you only have to compare to the largest one in the small list and to the smallest one in the large list. It would reduce the number of if-else's you had, but would require more overhead to track which one to compare to.

Infarction is correct. Probably the easiest way to start this solution is one value at a time. Find the min and max. When you understand that, add the second min and max. Etc.

Ok, thanks guys, I'll keep working at it, I should be able to find the min and max then work from there

This article has been dead for over six months. Start a new discussion instead.