diff --git a/SearchingAlgorithms/Java/BinarySearch.java b/SearchingAlgorithms/Java/BinarySearch.java new file mode 100644 index 0000000..27a1640 --- /dev/null +++ b/SearchingAlgorithms/Java/BinarySearch.java @@ -0,0 +1,53 @@ +// Sudarshan Hiray +// 4th October 2020 +// Given an Array of Integers and element to be searched, following program will search the element through Binary search. +// Elements MUST be sorted for binary search. +// Binary search uses Divide And Conquer technique. +// In each step, the algorithm compares the input element x with the value of the middle element in array. +// If the values match, return the index of the middle. Otherwise, if x is less than the middle element, +// then the algorithm recurs for left side of middle element, else recurs for the right side of the middle element. + +import java.util.Scanner; + +public class BinarySearch +{ + public static void main(String[] args){ + Scanner scanner = new Scanner(System.in); + + System.out.println("Please enter size of the array"); + int size = scanner.nextInt(); + System.out.println("Please enter "+size+ " elements of the array"); + System.out.println("Enter elements in Ascending order as Binary search can work only with Sorted elements"); + int[] intArray = new int[size]; + for(int i=0;i0 && intArray[i] right) + return -1; + int mid = (left + right)/2; + if(A[mid] == k) + return mid; + else if(A[mid] < k) + return binarySearch(A, mid+1, right, k); + else if(A[mid] > k) + return binarySearch(A, left, mid-1, k); + else + return -1; + } +} diff --git a/SearchingAlgorithms/Java/LinearSearch.java b/SearchingAlgorithms/Java/LinearSearch.java new file mode 100644 index 0000000..e7fe908 --- /dev/null +++ b/SearchingAlgorithms/Java/LinearSearch.java @@ -0,0 +1,39 @@ +// Sudarshan Hiray +// 4th October 2020 +// Given an Array of Integers and element to be searched, following program will search the element through Linear search. +// Linear search will go through all elements linearly even if element is at the end of the array. Hence its complexity is O(n). + + +import java.util.Scanner; + +public class LinearSearch +{ + public static void main(String[] args){ + Scanner scanner = new Scanner(System.in); + + System.out.println("Please enter size of the array"); + int size = scanner.nextInt(); + System.out.println("Please enter "+size+ " elements of the array"); + int[] intArray = new int[size]; + for(int i=0;i