From 4abb1aeddc75424363b64dd560ba8b109c8df05f Mon Sep 17 00:00:00 2001 From: Ashish Aggarwal <31507313+Ashish7129@users.noreply.github.com> Date: Mon, 5 Oct 2020 11:38:24 +0530 Subject: [PATCH] Added Linear Search in Java Added Linear Search in Java --- Searching/LinearSearch.java | 51 +++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Searching/LinearSearch.java diff --git a/Searching/LinearSearch.java b/Searching/LinearSearch.java new file mode 100644 index 0000000..0df8476 --- /dev/null +++ b/Searching/LinearSearch.java @@ -0,0 +1,51 @@ +/** + * Algorithm : Linear Search + * Description: Given an array of integers and you need to find a key or a number. If you finds the key in the array, it returns TRUE otherwise FALSE + * Time Complexity : O(n) + */ + +import java.util.*; + +public class LinearSearch { + private static final String ERROR_STRING = "Please provide a list of integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")"; + public static void main(String[] args) { + try { + // Returns TRUE + List listOfNumbers = new ArrayList(Arrays.asList(1,2,3,4,5)); + Integer keyToSearch = 5; + InputOutputMethod(listOfNumbers, keyToSearch); + + // Returns FALSE + keyToSearch = 6; + InputOutputMethod(listOfNumbers, keyToSearch); + + // Gives error as no input + listOfNumbers = new ArrayList(Arrays.asList()); + InputOutputMethod(listOfNumbers, keyToSearch); + } + catch(Exception e) { + System.out.println(ERROR_STRING); + } + } + + private static void InputOutputMethod(List listOfNumbers, Integer keyToSearch) { + if(listOfNumbers.size() >= 1){ + StringBuilder output = new StringBuilder(); + Boolean searched = linearSearch(listOfNumbers, keyToSearch); + System.out.println(searched); + }else{ + System.out.println(ERROR_STRING); + } + } + + private static Boolean linearSearch(List list, Integer keyToSearch) { + Boolean answer = false; + for (Integer number : list) { + if(number == keyToSearch) { + answer = true; + break; + } + } + return answer; + } +}