Efficient search of sorted numerical values

后端 未结 4 696
不思量自难忘°
不思量自难忘° 2021-02-06 15:06

I have an int[] array that contains values with the following properties:

  • They are sorted
  • They are unique (
4条回答
  •  长发绾君心
    2021-02-06 15:36

    I have one solution.
    you are saying array can be
    1)numbers are evenly distributed across the range
    2)there are quite long sequences of consecutive numbers.

    So, first we start a simple test to make sure whether its of type1 or type2.
    To test for type 1,
    lenght =array.length;
    range = array[length-1] - array[0];
    Now consider the values of array at
    { length(1/5),length(2/5),length(3/5),length(4/5)},
    If the array distribution is of type 1, then we approximately know what must be the value at array[i], so we check whether at those above 4 positions whether they are close to known values if its equal distribution.
    If they are close, then its equal distribution and so we can easily find any element in array.If we can't find element based on above approach, we consider it is of type 2.

    If above test Fails then it is of type 2, which means in the array there are few places where long sequences of consecutive numbers is present.

    so, we solve it in terms like binary search.Explanation is below
    *we first search in the middle of the array,(say at length/2, index as i)

    left =0,right=length;
    BEGIN:
    i=(left+right)/2;

    case a.1: our search number is greater than array[i]
    left=i;
    *Now we check at that position is there any long consecutive sequence is present, i.e
    array[i],array[i+1],array[i+2] are consecutive ints.

    case a.1.1: (If they are in consecutive),
    as they are consecutive ,and the sequence might be long, we directly search at particular index based on our search integer value.
    For example, if our search int is 10, and sequence is 5,6,7,8,9,10,11 15,100,103,
    and array[i]=5, then we directly search at array[i+10-5],
    If we find our search int, return it, else continue from case a.2 only [because it will obviously less than it] by setting right as
    right=(array[i+10-5])

    case a.1.2, if they are not consecutive
    continue from BEGIN;

    case a.2: our search number is less than array[i],
    *case a.2 is exactly similar to a.1
    *similarly check is there any back sequence , i.e array[i-2],array[i-1],array[i] are in sequence,
    If they are in consecutive sequence , search back to exact value as we did in case a.1.1
    If they are not consecutive, repeat similar to case a.1.2.

    case a.3, it is our search int,
    then return it.

    HOPE THIS helps

提交回复
热议问题