Skip to content

New Snippets in java (Searching Methods) #152

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions snippets/java/searching/binary-search.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
---
title: Binary Search
description: Searches a specific element in an array in optimised manner
author: SarvariHarshitha
tags: searching, binary-search
---

```java
public class BinarySearchRecursive {
public static int binarySearch(int[] arr, int low, int high, int key) {
if (low <= high) {
int mid = low + (high - low) / 2;

if (arr[mid] == key) {
return mid; // Key found
} else if (arr[mid] < key) {
return binarySearch(arr, mid + 1, high, key); // Search in the right half
} else {
return binarySearch(arr, low, mid - 1, key); // Search in the left half
}
}
return -1; // Key not found
}

public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int key = 30;

int result = binarySearch(numbers, 0, numbers.length - 1, key);

if (result != -1) {
System.out.println("Element found at index: " + result); //Result : Element found at index: 2
} else {
System.out.println("Element not found in the array.");
}
}
}

```
34 changes: 34 additions & 0 deletions snippets/java/searching/linear-search.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
---
title: Linear Search
description: Searches a specific element in an array
author: SarvariHarshitha
tags: searching, linear-search
---

```java
public class LinearSearch {
public static int linearSearch(int[] arr, int key) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == key) {
return i; // Return the index where the key is found
}
}
return -1; // Return -1 if the key is not found
}

public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int key = 30;

int result = linearSearch(numbers, key);

if (result != -1) {
System.out.println("Element found at index: " + result); // Result : Element found at 2
} else {
System.out.println("Element not found in the array.");
}
}
}


```
Loading