Skip to content

Commit 624a175

Browse files
authored
Add files via upload
1 parent d4724b1 commit 624a175

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

SearchingAlgorithms/BinarySearch.java

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import java.util.*;
2+
3+
class BinarySearch{
4+
public static void binarySearch(int arr[], int first, int last, int key){
5+
int mid = (first + last)/2;
6+
while( first <= last ){
7+
if ( arr[mid] < key ){
8+
first = mid + 1;
9+
}else if ( arr[mid] == key ){
10+
System.out.println("Element is found at index: " + mid);
11+
break;
12+
}else{
13+
last = mid - 1;
14+
}
15+
mid = (first + last)/2;
16+
}
17+
if ( first > last ){
18+
System.out.println("Element is not found!");
19+
}
20+
}
21+
public static void main(String args[]){
22+
Scanner input = new Scanner(System.in);
23+
System.out.print("Number of Values : ");
24+
int n = input.nextInt();
25+
System.out.println("Enter the Values in order : ");
26+
int[] array = new int[n];
27+
for (int i = 0; i < n; i++) {
28+
array[i] = input.nextInt();
29+
}
30+
//Arrays.sort(array); [IF ORDER IS NOT PRESENT]
31+
System.out.print("Enter the Value to search : ");
32+
int key = input.nextInt();
33+
binarySearch(array,0,n-1,key);
34+
}
35+
}

SearchingAlgorithms/LinearSearch.java

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import java.util.Scanner;
2+
3+
public class LinearSearch {
4+
public static void main(String[] args) {
5+
Scanner input = new Scanner(System.in);
6+
System.out.print("Number of Values : ");
7+
int n = input.nextInt();
8+
System.out.println("Enter the Values : ");
9+
int[] array = new int[n];
10+
for (int i = 0; i < n; i++) {
11+
array[i] = input.nextInt();
12+
}
13+
System.out.print("Enter the Value to search : ");
14+
int key = input.nextInt();
15+
int x = n+1;
16+
for (int i = 0; i < n; i++) {
17+
if (array[i] == key) {
18+
x = i;
19+
}
20+
}
21+
if (x == n+1) System.out.println("Key Value Not Found");
22+
else System.out.println("Key Value found at index " + x);
23+
}
24+
}

0 commit comments

Comments
 (0)