Skip to content
Advertisement

Search in a circularly-sorted array Java

i really got stuck on this and i’d love your help.
I’m trying to write a method with the signature:

JavaScript

The method gets as parameters two-dimensional array that is circularly-sorted, and a value to search for num. If the value num is in the mat array, the method returns true. If the num value is not in the mat array, the method returns false.

example for circularly-sorted array

The array is circular if all the values in Quarter 1 are really smaller than all those in Quarter 2, those in Quarter 2 are really smaller than all those in Quarter 3, and those in Quarter 3 are really smaller than all those in Quarter 4.

For example, the following array is circularly-sorted:

a bigger example of a circularly-sorted array

If the array mat is the array drawn above, and the number num is 22, the method returns the value true.
If the array mat is the array drawn above, and the number num is 23, the method will return the value false

The conditions:

  • The array is quadratic two-dimensional, meaning that the number of rows and columns is equal
  • The mat array is not null and is circularly-sorted. You do not need to check this.
  • The method should be as effective as possible, both in terms of time complexity and In terms of memory complexity.

Advertisement

Answer

The construction of this sort is such that the smallest element of each quarter is in the top left and the largest is in bottom left. You can check in which quarter the searched for element should be located and repeat the search in sub-quarters of that quarter.

An example implementation:

JavaScript

Full code

Advertisement