0% found this document useful (0 votes)
6 views2 pages

Java Search Algorithms Example

Uploaded by

vibesofcollege
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Java Search Algorithms Example

Uploaded by

vibesofcollege
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

import [Link].

Scanner;

public class SearchProgram {


static int binarySearch(int[] arr, int low, int high, int key) {
if (low > high) return -1;
int mid = (low + high) / 2;
if (arr[mid] == key) return mid;
if (arr[mid] > key) return binarySearch(arr, low, mid - 1, key);
return binarySearch(arr, mid + 1, high, key);
}

static int linearSearch(int[] arr, int index, int key) {


if (index == [Link]) return -1;
if (arr[index] == key) return index;
return linearSearch(arr, index + 1, key);
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

[Link]("Enter size of sorted array: ");


int n1 = [Link]();
int[] sorted = new int[n1];
[Link]("Enter elements of sorted array:");
for (int i = 0; i < n1; i++) sorted[i] = [Link]();
[Link]("Enter element to search in sorted array: ");
int key1 = [Link]();
int res1 = binarySearch(sorted, 0, n1 - 1, key1);
[Link](res1 == -1 ? "Not found" : "Found at index " + res1);

[Link]("Enter size of unsorted array: ");


int n2 = [Link]();
int[] unsorted = new int[n2];
[Link]("Enter elements of unsorted array:");
for (int i = 0; i < n2; i++) unsorted[i] = [Link]();
[Link]("Enter element to search in unsorted array: ");
int key2 = [Link]();
int res2 = linearSearch(unsorted, 0, key2);
[Link](res2 == -1 ? "Not found" : "Found at index " + res2);
}
}
Sample Output 1:
Enter size of sorted array: 5
Enter elements of sorted array:
2 4 6 8 10
Enter element to search in sorted array: 8
Found at index 3

Enter size of unsorted array: 6


Enter elements of unsorted array:
739165
Enter element to search in unsorted array: 1
Found at index 3

Sample Output 2:
Enter size of sorted array: 4
Enter elements of sorted array:
1357
Enter element to search in sorted array: 4
Not found

Enter size of unsorted array: 5


Enter elements of unsorted array:
10 20 30 40 50
Enter element to search in unsorted array: 15
Not found

You might also like