• 카테고리

    질문 & 답변
  • 세부 분야

    알고리즘 · 자료구조

  • 해결 여부

    미해결

순차탐색 : 다른버젼 질문입니다.

16.08.20 08:28 작성 조회수 162

0

이번 강의를 들으면서 자바를 배우기 시작해서 제가 순전히 자바를 못하기 때문에 하는 질문이긴 하지만... 강의 중 나오는 순차탐색 : 다른 버젼을 직접 짜보았는데 ArrayIndexOutofBoundsException 이라는 오류가 뜹니다. 아래가 저의 코드입니다. import java.util.Scanner; public class linearSearch{ public static void main(String[] args){ int [] arr = {0}; int target; System.out.println("type elements of array"); for(int i =0; i end){ return -1; }else{ middle = (begin+end)/2; if(data[middle] == target){ return middle; } index = search(data, begin, middle-1, target); if(index != -1){ return index; } else{ return search(data, middle+1, end, target); } } } }

답변 3

·

답변을 작성해보세요.

2

그리고 
 Scanner sc = new Scanner(System.in);
이 문장이 for문 내부가 아니라 바깥에 있어야 겠죠.

1

메론녹차님의 프로필

메론녹차

2016.08.22

배열 선언시 다음과 같이 하셨는데 `int [] arr = {0};` 이렇게 하면 배열 arr에는 0만 들어가있는, size 1만큼의 배열이 생성 됩니다. 방 크기가 1인 배열에 10개의 데이터를 넣으려고 하니까 index에러가 생기죠. 이렇게 하지 마시고, int[] arr = new int[10]; 으로 선언하시면 될겁니다.

0

신승윤님의 프로필

신승윤

질문자

2016.08.20

질문에 코드가 읽기 불편하게 올라가서 ...

import java.util.Sacnner;
public class linearSearch{
public static void main(String[] args){
    int [] arr = {0};int target;
    System.out.println(“type elements of array”);
    for(int i =0; i<10; i++){
        Scanner sc = new Scanner(System.in);
        arr[i] = (sc.nextInt());
    } 
    System.out.println("type the target element");
    Scanner t = new Scanner(System.in);
    target = t.nextInt();
    search(arr, 0, arr.length-1, target);

    public static int search(int [] data, int begin, int end, int target){
        int middle,index;
        if(begin > end){
            return -1;
        }else{
            middle = (begin+end)/2;
            if(data[middle] == target){
                return middle; }
            index = search(data, begin, middle-1, target); 
            if(index != -1){
                return index;
            }else{
                return search(data, middle+1, end, target);
            }
        }
    }
}