
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implement Linear Search in Java
Linear search is a very simple search algorithm. In this type of search, a sequential search is done for all items one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the end of the data collection.
Algorithm
1.Get the length of the array. 2.Get the element to be searched store it in a variable named value. 3.Compare each element of the array with the variable value. 4.In case of a match print a message saying element found. 5.else, print a message saying element not found
Example
public class LinearSearch { public static void main(String args[]){ int array[] = {10, 20, 25, 63, 96, 57}; int size = array.length; int value = 63; for (int i=0 ;i< size-1; i++){ if(array[i]==value){ System.out.println("Element found index is :"+ i); }else{ System.out.println("Element not found"); } } } }
Output
Element found index is :3
Advertisements