简体   繁体   中英

Java loop through array

How do you loop through an array until you you reach the last 50 elements of your array then?? say I have this binary search code:

public class Binary
{
public static final int NOT_FOUND = -1;


public static <AnyType extends Comparable<? super AnyType>>
              int binarySearch( AnyType [ ] a, AnyType x )
{
    int low = 0;
    int high = a.length - 1;
    int mid;

    while( low <= high )
    {
        mid = ( low + high ) / 2;

        if( a[ mid ].compareTo( x ) < 0 )
            low = mid + 1;
        else if( a[ mid ].compareTo( x ) > 0 )
            high = mid - 1;
        else
            return mid;
    }

    return NOT_FOUND;     // NOT_FOUND = -1
}

// Test program
public static void main( String [ ] args )
{
    int SIZE = 8;
    Integer [ ] a = new Integer [ SIZE ];
    for( int i = 0; i < SIZE; i++ )
        a[ i ] = i * 2;

    for( int i = 0; i < SIZE * 2; i++ )
        System.out.println( "Found " + i + " at " +
                             binarySearch( a, i ) );

  }
}

I would like to search the given array till I reach to the last 50 elements of this array, then the search is concluded with sequential look up of 50 elements. My question is that how can I construct such a loop and how to jump to the method that does the linear search.

Before you calculate mid , do something like

if(high - low + 1 <= 50) return linearSearch(low, high, a, x);

Then your linearSearch just has to iterator from low to high to find x , or else return NOT_FOUND .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM