From 882158c5972fc222e42fe1323983933ab17cff13 Mon Sep 17 00:00:00 2001 From: TharunBalaji2004 Date: Wed, 11 Oct 2023 17:19:06 +0530 Subject: [PATCH] Added Linear Search algorithm --- BinarySearch.java | 48 +++++++++++++++++++++++++++++++++++++++++++++++ LinearSearch.java | 40 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 BinarySearch.java create mode 100644 LinearSearch.java diff --git a/BinarySearch.java b/BinarySearch.java new file mode 100644 index 0000000..6c8ceb8 --- /dev/null +++ b/BinarySearch.java @@ -0,0 +1,48 @@ +import java.util.Scanner; + +public class BinarySearch { + public static int binarySearch(int[] array, int key){ + int start = 0; + int end = array.length - 1; + while(start <= end){ + int mid = (start + end) / 2; + if(key == array[mid]){ + return mid; + } + if(key < array[mid]){ + end = mid - 1; + }else{ + start = mid + 1; + } + } + return -1; + } + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + System.out.print("Enter number of elements: "); + int n = sc.nextInt(); + + int[] arr = new int[n]; + System.out.println("Enter elements: "); + for (int i = 0; i < n; i++) { + arr[i] = sc.nextInt(); + } + + System.out.print("Enter key to search: "); + int key = sc.nextInt(); + + int index = binarySearch(arr, key); + if (index == -1) { + System.out.println("Key not found"); + } else { + System.out.println("Key found at index " + index); + } + + sc.close(); + } +} + +// Time Complexity: O(log n) +// Space Complexity: O(1) \ No newline at end of file diff --git a/LinearSearch.java b/LinearSearch.java new file mode 100644 index 0000000..adc24f4 --- /dev/null +++ b/LinearSearch.java @@ -0,0 +1,40 @@ +import java.util.Scanner; + +public class LinearSearch { + public static int linearSearch(int[] arr, int key) { + for (int i = 0; i < arr.length; i++) { + if (key == arr[i]) { + return i; + } + } + return -1; + } + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + System.out.print("Enter number of elements: "); + int n = sc.nextInt(); + + int[] arr = new int[n]; + System.out.println("Enter elements: "); + for (int i = 0; i < n; i++) { + arr[i] = sc.nextInt(); + } + + System.out.print("Enter key to search: "); + int key = sc.nextInt(); + + int index = linearSearch(arr, key); + if (index == -1) { + System.out.println("Key not found"); + } else { + System.out.println("Key found at index " + index); + } + + sc.close(); + } +} + +// Time Complexity: O(n) +// Space Complexity: O(1)