Java Program To Implement Linear Search Algorithm - For Intermediates / Advanced

Published: 19 November 2017
on channel: Computer Analyst
66
2

Code of Linear Search :

import java.util.*;

public class LSearch{

static int position;

public static void main(String args[]){

Scanner sc = new Scanner(System.in);

int size, item;

position = -1;// signifies the state that the element is not found yet..

//The size of the array will be entered..

System.out.println("Enter the size of the array :");

size = sc.nextInt();

//creating an array..

int[] arr = new int[size];

//now code to take elements in the array..

System.out.println("Enter the elements of the array :");

for(int i = 0; i < size; i++){
arr[i] = sc.nextInt();
}

//Now entering the element to be searched in the array..

System.out.println("Enter the element to be searched in the array :");

item = sc.nextInt();

/*Now calling a static method linearSearch method to store the value in the position in the variable..
which will be defined later in the code.. The reason to call static method is that since main is a static method so any method called from the main method must be static.. :)*/

position = linearSearch(size, item, arr);

if(position == -1){
System.out.println(item+" is not found .");
} else{
position = position + 1;
System.out.println(item+" is found at "+position);
}
sc.close();
}
public static int linearSearch(int size, int item, int[] arr){

//main logic

for(int i = 0; i < size; i++){

if(arr[i] == item){
return i;
}
}
return -1;
}
}

/* Explanation: Suppose size = 5, therefore, taking random 5 integer values in the array as

arr[5] = {1, 3, 5, 7, 9}

Now, taking the item = 5 to be searched in the array, so, we can it is there in the array at 2nd index..
.
.
position will be = 2 and then position = position + 1 = 2 + 1 = 3 to show the real position of the element in the array..
.
.
output will be 5 is found at 3
..
Now taking item = 10, so 10 is not in the array so, It will have position = -1 , the output will be 10 is not found..
*/

🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻

Thanks for watching..

Plz do subscribe, like and share..

For any query, plz comment in the comment section below..

Use Headphone or Earphone for better hearing of audio..

🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻

Video Link To Set Path For Java in Windows :
   • How To Set Path For Java in Windows - For ...  

🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻

Follow On :
✅Instagram :   / computer_analyst.yt  
✅Google+ : https://plus.google.com/b/11676538144...
✅Twitter :   / yt_c_analyst  


On this page of the site you can watch the video online Java Program To Implement Linear Search Algorithm - For Intermediates / Advanced with a duration of hours minute second in good quality, which was uploaded by the user Computer Analyst 19 November 2017, share the link with friends and acquaintances, this video has already been watched 66 times on youtube and it was liked by 2 viewers. Enjoy your viewing!