algorithm - Best way to find a number in an array that's "out of order"? -


i have array of length 10 filled numbers 0-9.

the numbers (for part) in sequential order. number @ starting index can number, , whether numbers in ascending or descending order unknown (the numbers wrap around once hit min/max number - 0 once reaches 9, , vice-versa).

exactly 1 of these numbers not in order (as if it's been plucked out , randomly inserted array).

example:

[4, 3, 1, 0, 9, 8, 7, 2, 6, 5] 

the number 2 @ index 7 out of order. "gap" in numbers between indexes 1 , 2 okay, , neither number 3 or 1 considered out of order.

what's best way pinpoint index of out-of-order number?

more examples - out of place numbers marked *:

[2, 3, *0, 4, 5, 6, 7, 8, 9, 1] [5, 6, 7, 9, *8, 0, 1, 2, 3, 4] [7, 6, 5, 4, 3, *8, 2, 1, 0, 9] [0, *5, 1, 2, 3, 4, 6, 7, 8, 9] [4, 3, *0, 2, 1, 9, 8, 7, 6, 5]  

to find number out-of-order have @ every element in array. so, have iterate on entire array complexity o(n).

when loop through array, should

  • calculate absolute value of difference between previous number , current number.
  • calculate absolute value of difference between current number , next number

if both above differences greater 1 , not equal n-1 (when difference n-1, point array flips), number out of order.


Comments

Popular posts from this blog

.htaccess - First slash is removed after domain when entering a webpage in the browser -

Automatically create pages in phpfox -

c# - Farseer ContactListener is not working -