0

I know similar questions have been asked, but I have an array... which has been shuffled, so elements are at random indexes.

int[] cells = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};

How can I write an if statement, that determines if the cells array is in the order of:

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0};

I would like the if to return true if the entire array is sorted, not true for each index/element.

Thanks for the help, i managed to find an answer using an Int that increments each time a number is in the correct index, once iterated 16 times, if that int == cells.length, then the array is sorted, here is the sorted array...

sorted = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0};
int correct = 0;
        for (i = 0; i < cells.length; i++){
            if (cells[i] == sorted[i]){
                correct++;
                if (correct == cells.length){
                    return true;
                }
            }
            else{
                return false;
            }
        }
4
  • I guess you need a recursive function to check it out instead of an if statement. Commented May 21, 2018 at 6:37
  • use Collections.shuffle(); i hope it will help you! Commented May 21, 2018 at 6:39
  • You could create a hard copy of the array, order it and then compare if they are equals. Lot of effort and runtime computation, so you should IMHO first of all consider why would you need such a check. Commented May 21, 2018 at 6:47
  • By the way the 0 is at the end of the array. Is this intended? Commented May 22, 2018 at 9:40

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.