이진탐색을 재귀함수를 사용하여 구현해보았다.
import java.util.Scanner;
public class BinarySearch {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in) ;
int[] arr= {0,1,2,3,4,5,6,7,8,9,10};
int num=0;
for(int i=0;i<arr.length;i++) {
System.out.print(arr[i]+" ");
}
while(num>=0) {
System.out.println("\n검색할 숫자를 입력하세요");
num = sc.nextInt();
System.out.println(binary(arr,0,arr.length-1,num));
}
}
public static int binary(int []a,int start, int end, int key) {
int pc = start +((end-start)/2);
if(start<=end) {
if(a[pc]==key)return pc;
else if(a[pc]>key)return binary(a,start,pc-1,key);
else return binary(a,pc+1,end,key);
}
else return -1;
}
}
'Java' 카테고리의 다른 글
정렬 알고리즘 : 버블정렬 (0) | 2022.07.18 |
---|---|
급여관리프로그램 (0) | 2022.07.15 |
팩토리얼 (0) | 2022.07.14 |
숫자를 입력 받아 교차하여 가장 작은 수 출력하기 2 (0) | 2022.07.12 |
100~9999999 범위를 갖는 변수 X와 X~9999999 범위를 갖는 변수 Y를 입력 받아 X와Y 사이의 모든 정돈된 수와 전체 개수를 출력하는 프로그램을 작성해라 (0) | 2022.07.11 |