데이터 구조 - 절반 찾기

3277 단어 데이터 구조
선형 방식 으로 반 으로 찾기:
Binary_Search(int arr[],int key,int lowIndex,int upperIndex)

{

    int middleIndex = 0;

    while(lowIndex <= upperIndex)

    {

        middleIndex = lowIndex + (upperIndex - lowIndex) / 2;

        if(arr[middleIndex] == key)

        {

            return middleIndex;

        }

        if (key > arr[middleIndex])

        {

            lowIndex = middleIndex + 1;

        }

        else

        {

            upperIndex = middleIndex - 1;

        }

    }



    return -1;

}

재 귀 방식 으로 반 으로 찾기:
Binary_Search_Recursive(int arr[],int key,int lowIndex,int upperIndex)

{

    if (lowIndex <= upperIndex)

    {

        int middleIndex = lowIndex + (upperIndex - lowIndex) / 2;

        if(arr[middleIndex] == key)

        {

            return middleIndex;

        }

        else if(arr[middleIndex] < key)

        {

            lowIndex = middleIndex + 1;

            Binary_Search_Recursive(arr,key,lowIndex,upperIndex);

        }

        else

        {

            upperIndex = middleIndex - 1;

            Binary_Search_Recursive(arr,key,lowIndex,upperIndex);

        }

    }

    else

    {

        return -1;    

    }

}

좋은 웹페이지 즐겨찾기