Algorithms
Sequential Search Algorithm (Linear Search)
seoca
2019. 7. 30. 06:02
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[] = {7, 4, 3, 1, 5};
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