티스토리 뷰

 

 

 

Sequential Search Algorithm (Linear Search) 순차탐색

 

Less used than binary search and Hash Table. Big-O notation for Sequential Search is O(n) which is relatively slower than others. 

 

 

public class Main {
    public static void main(String[] args) {
        int arr[] = {74315};
        int x = 3;
        int answer = linearSearch(arr, x);
 
        if(answer == -1){
            System.out.println("No element matched");
        }else{
            System.out.println("Element is present at index " + answer); //2
        }
    }
 
    private static int linearSearch(int arr[], int x) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == x) {
                return i;
            }
        }
        return -1;
    }
}
 

 

 

 

 

Reference

https://www.geeksforgeeks.org/linear-search/

 

'Algorithms' 카테고리의 다른 글

Comparison performing contains() for ArrayList and HashSet  (0) 2019.08.31
Insertion Sort  (0) 2019.08.01
Selection Sort  (0) 2019.07.27
Bubble Sort  (0) 2019.07.25
Recursion in Java  (0) 2019.07.24