Add java code for linear search

pull/18/head
sal81 2021-01-21 05:17:01 +05:30
parent 8ff6a99172
commit 5a25bd3466
2 changed files with 27 additions and 0 deletions

View File

@ -11,3 +11,9 @@
1. [Linear Search](python/linear-search.py) 1. [Linear Search](python/linear-search.py)
2. [Binary Search](python/binary-search.py) 2. [Binary Search](python/binary-search.py)
### Java
1. [Linear Search](java/linear-search.java)

View File

@ -0,0 +1,21 @@
//Linear search to check for a given key in an array
public class MyLinearSearch{
public static int linearSearch(int[] arr, int key){
for(int i=0;i<arr.length;i++){
if(arr[i] == key){
return i;
}
}
return -1;
}
public static void main(String args[]){
int[] arr1= {10,20,30,50,70,90};
int key = 30;
System.out.println(key+" is present and is found at index: "+linearSearch(arr1, key));
}
}
// For running in terminal rename this file to MyLinearSearch.java
//then run the commands <javac MyLinearSearch.java> followed by <java MyLinearSearch>
//It will generate and a MyLinearSearch.class file which is a file containing java bytecode that is executed by JVM.