Algorithm
이진탐색 (BinarySearch) 예제 (C#)
doublesweet
2021. 12. 8. 13:25
// 정렬된 숫자 array 에서 이진탐색
private int BinarySearch(int[] array, int target)
{
int last = array.Length - 1;
for (int first = 0; first <= last; )
{
int center = (first + last) / 2;
switch (Compare(target, array[center]))
{
case 0 :
return center;
case 1 :
first = center + 1;
break;
case 2 :
last = center - 1;
break;
}
}
}
// 비교
private int Compare(int a, int b)
{
if (a == b)
{
return 0;
}
return a > b ? 1 : 0;
}