Merge pull request #18 from sal81/java-linear-search

Add java code for linear search
pull/19/head^2
Ming Tsai 2021-01-21 08:48:53 -04:00 committed by GitHub
commit b6b6b589ee
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 0 deletions

View File

@ -11,3 +11,9 @@
1. [Linear Search](python/linear-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.