Linear Search Algorithm | Java Liner Search
Linear search is the simplest form of search used for searching. In linear search we compare each element in the list with the element we want to search and then returns the index of that element if match is found.
Problem- How to search the index of an element inside an array using linear search algorithm in java?
Solution-Suppose we have an array of integers - 12,14,1,55,6,33,6,12,34,22,45,60
Now we will loop through this array and search for the required element and if we find the element, we will print the index of that item.
Problem- How to search the index of an element inside an array using linear search algorithm in java?
Solution-Suppose we have an array of integers - 12,14,1,55,6,33,6,12,34,22,45,60
Now we will loop through this array and search for the required element and if we find the element, we will print the index of that item.
package com.tutorialsinn.java; public class LinearSearch { public static void main(String args []){ int arr [] = {12,14,1,55,6,33,6,12,34,22,45,60}; for(int i=0; i<:arr.length; i++){ if(6 == arr[i]){ System.out.println("element found at index "+i); break; } } } }Output -
element found at index 4
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment