3
Sun Nov 26 2023 17:37:08 GMT+0000 (Coordinated Universal Time)
Saved by
@jack
public class SearchAlgorithms {
public static int linearSearch(int[] array, int target) {
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
return i;
}
}
return -1;
}
public static int binarySearch(int[] array, int target) {
int left = 0;
int right = array.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (array[mid] == target) {
return mid;
} else if (array[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
public static void main(String[] args) {
int[] array = {2, 5, 8, 12, 16, 23, 38, 45, 50};
int targetLinear = 16;
int targetBinary = 38;
int linearResult = linearSearch(array, targetLinear);
if (linearResult != -1) {
System.out.println("Linear Search: Element " + targetLinear + " found at index " + linearResult);
} else {
System.out.println("Linear Search: Element " + targetLinear + " not found in the array");
}
int binaryResult = binarySearch(array, targetBinary);
if (binaryResult != -1) {
System.out.println("Binary Search: Element " + targetBinary + " found at index " + binaryResult);
} else {
System.out.println("Binary Search: Element " + targetBinary + " not found in the array");
}
}
}
content_copyCOPY
https://www.programiz.com/java-programming/online-compiler/
Comments