본문 바로가기

old/Programming

리니어 서치 알고리즘이란

반응형

리니어 서치 알고리즘 Linear Search Algorithm

Definition

데이터 스트럭쳐에 담긴 아이템을 찾는 알고리즘 중 하나
리스트에 있는 아이템을 하나씩 확인해가며 비교한후 아이템을 찾는다.

Time complexity

O(n)

Example

import java.util.NoSuchElementException;

public class Main {

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 2, 2, 5};
        System.out.println(getIndexValueArr(nums, 5));
    }

    public static int getIndexValueArr(int[] input, int value) {
        for (int i = 0; i < input.length; ++i) {
            if (input[i] == value) {
                return i;
            }
        }
        throw new NoSuchElementException();
    }
}

Explanation

step 1

step 2

step 3

step 4

step 5

반응형