Zahra Mahmood
Zahra Mahmood

Reputation: 35

How do I check to see if my array is in ascending order?

So I have an array board[][] whose values keep shuffling around. It is a square array with dimensions d*d. I want to check the array to see if all of its values are in ascending order.

for (int i = 0; i < d; i++)
{
    for (int j = 0; i < d; i++)
    {
        if (board[i][j] == (d * i) + j + 1)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

the problem is that as soon as the first element in the array board[0][0] = 1, it returns true, and ends my code. I don't know how to implement it so that it doesn't return true until all the elements in the array are in ascending order, from 1 to (d*d - 1).

Thank you!

Upvotes: 0

Views: 2957

Answers (4)

noelicus
noelicus

Reputation: 15055

If I understood your question correctly I think you want to do this:

int Previous = board[0][0];
for (int i = 0; i < d; i++)
{
    for (int j = 0; j < d; j++)
    {
        if (board[i][j] < Previous)
        {
            return false;
        }

        Previous = board[i][j];
    }
}
return true; // Only at the end do we know that all elements are in ascending order

Problems with what you have are:

  1. You are returning on either condition instead of returning after all values have been checked
  2. Your second for loop is wrong and references i, not j
  3. Your comparison is comparing board values against the indexes, not other board values

Upvotes: 3

SRF
SRF

Reputation: 979

This should work

for (int i = 0; i < d; i++)
{
    for (int j = 0; j < d; j++)
    {
        if (board[i][j] != (d * i) + j + 1)
        {
           return false;
        }
    }
}
return true;

Upvotes: 2

fahim
fahim

Reputation: 23

1) First what you mean by ascending order (vertically, horizontally or in diagonal ?) 2) Replace your if statement if ((board[i][j] > board[i][j+1]) || (board[i][j] > board[i+1][j]))

Upvotes: 0

szx
szx

Reputation: 6936

Try replacing return true with continue:

for (int i = 0; i < d; i++)
{
    for (int j = 0; i < d; i++)
    {
        if (board[i][j] == (d * i) + j + 1)
        {
            continue;
        }
        else
        {
            return false;
        }
    }
}

You can also remove the continue clause completely if you reverse the condition:

        if (board[i][j] != (d * i) + j + 1)
        {
            return false;
        }

Upvotes: 1

Related Questions