Hi I am sort of having a little trouble with a part of my program. First off let me tell you a couple of the variables. Let m be the number of rows and let n be the number of columns in a 2D array. Let i be the counter for row m and j be the counter for column n. Let spreadsheet[i][j] contain the matrix with dimensions m and n that the user chose. This matrix is populated with numbers. If the user was asked to choose a row they would like to find the Median of, how would I go about that? My attempt:

`float Median;

        for (int j = 0; j < n; j++)
        {
            for (int k = 0; k < j; k++)
            {
                if (spreadsheet[i][j] < spreadsheet[j][k])
                {
                    int temp = spreadsheet[i][j];
                    spreadsheet[i][j] = spreadsheet[j][k];
                    spreadsheet[j][k] = temp;
                }
            }
        }

            if (n % 2 == 0)
            {
                for (int j = 0; j < n; j++)
                Median = ((spreadsheet[i-1][j]/2) + (spreadsheet[i-1][j]/2)-1)/2;
                cout << "The Median of row " << i << " = " << Median << ".\n";

            }

            if (n % 2 != 0)
            {
                for (int j = 0; j < n; j++)
                Median = spreadsheet[i-1][j]/n;
                cout << "The Median of row " << i << " = " << Median << ".\n";
            }`

I think that if you break this problem down it will be much easier. You want the median of one row, so you can isolate it, and possibly pass it to a median function. Then all you need to write is this:

float calculateMedian(float data[], int datalen);

This function will be easier to write then trying to muttle around multiple dimensions.

I guess the idea of your code is to sort the row elements and then pick the middle one as the median. However, your code is full of mistakes. The strategy is not optimal, but it should work, start by fixing all the little mistakes in the code, and it should work.

For a better solution, you should look into "selection algorithms".

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