Limited access

Upgrade to access all content for this subject

A student wants to design a method that performs a search on a sorted List. If the search key is larger than the middle element, a sequential search is performed on only the second half of the List. And if the search key is less than the middle element, a sequential search is performed on only the first half of the List.

Which of the following methods accomplishes this task?

I.

public static int search1(List<Integer> L, int key)
{
    if (key >  L.get(L.size()/2))
    {
        for (int i = L.size()/2 + 1; i< L.size(); i++)
        {
            if (key == L.get(i))
                return i;
        }
    }
    else if (key < L.get(L.size()/2))
    {
        for (int i = L.size()-1; i >= 0; i--)
        {
            if (key == L.get(i))
            return i;
        }
    }
    else
        return L.size()/2;

    return -1;
}

II.

public static int search2(List<Integer> L, int key)
{
    int x = 0;
    if (key > L.get(L.size()/2))
        x = 1;
    else if (key < L.get(L.size()/2))
        x = 2;
    else
        return -1;

    if (x == 1)
    {
        for (int i = L.size()/2 + 1; i < L.size(); i++)
        {
            if (key == L.get(i))
                return i;
        }
    }
    else if (x == 2)
    {
        for (int i = L.size()/2 - 1; i >= 0; i--)
        {
            if (key == L.get(i))
                return i;
        }
    }

    return L.size()/2;
}

III.

public static int search3(List L, int key)
{
    int x = 0;
    if (key > L.get(L.size()/2))
        x = 1;
    else if (key < L.get(L.size()/2))
        x = 2;
    else
        return L.size()/2;

    if (x == 1)
    {
        for (int i = L.size()/2 + 1; i < L.size(); i++)
        {
            if (key == L.get(i))
                return i;
        }
    }
    else if (x == 2)
    {
        for (int i = L.size()/2 - 1; i >= 0; i--)
        {
            if (key == L.get(i))
                return i;
        }
    }

    return -1;
}
A

I only.

B

II only.

C

III only.

D

I and II only.

E

I, II, and III.

Select an assignment template