Find the time [j] = j in O (log n)

How can I find if a sorted array has an element a [j] = j in O (log n) time? (no duplicates)

+3
source share
5 answers

If the array has integers and cannot contain duplicates, you can simply use binary search.

eg. let's say we have an array:

a[0] == -30
a[1] == 1
a[2] == 200
a[3] == 200
a[4] == 204
a[5] == 205
a[6] == 206
a[7] == 207
  • First try [gender (avg (0.7))] (i.e. [3]). This is equal to 200. 200 is also large.
  • So, go to the bottom half. Try a [gender (avg (0,2))] (ie a [1]). This is 1. Hooray!

Your binary search will either successfully find some j for which [j] == j, or it will fail, after completing the search for places. Since the binary search is O (log n), during this time you will know the value of j or that such j does not exist.

, j , .

+13

, . : a [2k] = 2k + 1, a [2k + 1] = 2k + 1 2k + 2. [2k + 1] k.

, . [1] -1 [n] -n. , - . , [n/2] -n/2. ( ), (1, n/2) (n/2, n) . .

+8

, :

#include <stdio.h>

int
find_elt_idx_match( int *a, int lo, int hi )
{
  int elt, idx;
  while ( lo <= hi )
    {
      idx = lo + ( hi - lo ) / 2; /* Thanks, @andand */
      elt = a[ idx ];
      if ( elt == idx )
        {
          return 1;
        }
      if ( elt < idx )
        {
          lo = idx + 1;
        }
      else
        {
          hi = idx - 1;
        }
    }
  return 0;
}

int
main( void )
{
  int a[ 100 ];
  /* fill a */
  /* ... */
  printf( "idx:elt match? %c\n", find_elt_idx_match( a, 0, 99 ) ? 'y' : 'n' );
  return 0;
}
+1
public int getFirstMatchedIndex(int[] oArry)
        {            
            int i = 0;
            while(i < oArry.Length )
            {
                if (oArry[i] == i)
                    return i;
                else if (oArry [i] > i)
                    i=oArry [i];
                else
                    i++;

            }
            return -1;
        }
0

If duplicates are not allowed and your list is sorted according to the obvious order a [i] a [i + 1] (strictly less, not equal!), Then it is also true that a [i] -i <a [i + 1 ] - i, it follows from this that a [i] -i <= a [i] - (i + 1). (Note that the inequality becomes "<=".) In other words, the values ​​of a [i] -i, in your list, are in order. Find the value 0 = a [i] -i using a binary search in a sorted list.

0
source

Source: https://habr.com/ru/post/1771839/


All Articles