Skip to content

Commit

Permalink
Merge pull request #1 from anushka-deshpande/anushka-deshpande-Search…
Browse files Browse the repository at this point in the history
…ing-Java

Linear and Binary Search in Java
  • Loading branch information
anushka-deshpande authored Oct 1, 2020
2 parents ddfafbf + 05c01dc commit 1f1c091
Showing 1 changed file with 68 additions and 0 deletions.
68 changes: 68 additions & 0 deletions Searching and Sorting/Java/Searching.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import java.io.*;
import java.util.*;

public class Searching
{
public static void main(String[] args)throws IOException
{
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
Scanner sc = new Scanner(System.in);

System.out.print("Length of Array: ");
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("Element to be searched: ");
int s = sc.nextInt();

Searching obj = new Searching();
int linear = obj.Linear(arr.clone(), s);

int[] sortedArr = Arrays.copyOf(arr, n);
Arrays.sort(sortedArr);
int binary = obj.Binary(sortedArr, 0,n-1,s);

System.out.println("Linear Search element found at: " + linear);
System.out.println("Binary Search element found it: " + binary);

}

public int Linear(int [] arr, int s)
{
int loc = -1;
for(int i=0;i<arr.length;i++)
{
if(arr[i] == s)
{
loc = i;
}
}
return loc;
}

public int Binary(int [] arr, int l, int r, int x)
{
if(r >= l)
{
int mid = (l + r)/2;

if(arr[mid] == x)
return mid;

else if(arr[mid] > x)
{
return Binary(arr, l, mid - 1, x);
}
else
{
return Binary(arr, mid+1, r,x);
}
}
return -1;
}
}

0 comments on commit 1f1c091

Please sign in to comment.