Skip to content

Commit e957812

Browse files
Add files via upload
1 parent ef1eb88 commit e957812

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
---
2+
title: Binary Search
3+
description: Searches a specific element in an array in optimised manner
4+
author: SarvariHarshitha
5+
tags: searching, binary-search
6+
---
7+
8+
```java
9+
public class BinarySearchRecursive {
10+
public static int binarySearch(int[] arr, int low, int high, int key) {
11+
if (low <= high) {
12+
int mid = low + (high - low) / 2;
13+
14+
if (arr[mid] == key) {
15+
return mid; // Key found
16+
} else if (arr[mid] < key) {
17+
return binarySearch(arr, mid + 1, high, key); // Search in the right half
18+
} else {
19+
return binarySearch(arr, low, mid - 1, key); // Search in the left half
20+
}
21+
}
22+
return -1; // Key not found
23+
}
24+
25+
public static void main(String[] args) {
26+
int[] numbers = {10, 20, 30, 40, 50};
27+
int key = 30;
28+
29+
int result = binarySearch(numbers, 0, numbers.length - 1, key);
30+
31+
if (result != -1) {
32+
System.out.println("Element found at index: " + result); //Result : Element found at index: 2
33+
} else {
34+
System.out.println("Element not found in the array.");
35+
}
36+
}
37+
}
38+
39+
```
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
---
2+
title: Linear Search
3+
description: Searches a specific element in an array
4+
author: SarvariHarshitha
5+
tags: searching, linear-search
6+
---
7+
8+
```java
9+
public class LinearSearch {
10+
public static int linearSearch(int[] arr, int key) {
11+
for (int i = 0; i < arr.length; i++) {
12+
if (arr[i] == key) {
13+
return i; // Return the index where the key is found
14+
}
15+
}
16+
return -1; // Return -1 if the key is not found
17+
}
18+
19+
public static void main(String[] args) {
20+
int[] numbers = {10, 20, 30, 40, 50};
21+
int key = 30;
22+
23+
int result = linearSearch(numbers, key);
24+
25+
if (result != -1) {
26+
System.out.println("Element found at index: " + result); // Result : Element found at 2
27+
} else {
28+
System.out.println("Element not found in the array.");
29+
}
30+
}
31+
}
32+
33+
34+
```

0 commit comments

Comments
 (0)