Created
January 19, 2018 01:56
-
-
Save milon/f818e073883ee32f00f584ded8f7b11d to your computer and use it in GitHub Desktop.
Linear Search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Linear Search | |
import java.util.Scanner; | |
public class LinearSearch{ | |
public static int linearSearch(int a[], int key) { | |
for(int i=0;i<a.length;i++) | |
if(a[i] == key) | |
return i+1; | |
return 0; | |
} | |
public static void main(String args[]) { | |
Scanner input = new Scanner(System.in); | |
System.out.println("Linear Search"); | |
System.out.print("Enter the number of element in array: "); | |
int n = input.nextInt(); | |
int arr[] = new int[n]; | |
System.out.print("Enter " + n + " numbers: "); | |
for(int i=0;i<n;i++) | |
arr[i] = input.nextInt(); | |
System.out.print("Enter the searching key: "); | |
int key = input.nextInt(); | |
if(linearSearch(arr, key) != 0) | |
System.out.println("Key found at " + linearSearch(arr, key) + " position."); | |
else | |
System.out.println("Key not found."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment