Computer Applications
Write a program to search for an ITEM using binary search in array X[10].
Java
Java Arrays
5 Likes
Answer
import java.util.Scanner;
public class KboatBinarySearch
{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
int X[] = new int[10];
System.out.println("Enter array in ascending order : ");
for(int i = 0; i < 10; i++)
{
X[i] = in.nextInt();
}
System.out.println("Input Array is:");
for (int i = 0; i < 10; i++) {
System.out.print(X[i] + " ");
}
System.out.println();
System.out.println("Enter search item :" );
int item = in.nextInt();
int l = 0, h = 9, index = -1;
while (l <= h) {
int m = (l + h) / 2;
if (X[m] < item)
l = m + 1;
else if (X[m] > item)
h = m - 1;
else {
index = m;
break;
}
}
if (index == -1) {
System.out.println("Search item not found");
}
else {
System.out.println(item + " found at index " + index);
}
}
}
Variable Description Table
Program Explanation
Output
![BlueJ output of Write a program to search for an ITEM using binary search in array X[10]. BlueJ output of Write a program to search for an ITEM using binary search in array X[10].](https://cdn1.knowledgeboat.com/img/sa10/c7-arrays-p44.jpg)
Answered By
2 Likes
Related Questions
Write a program Lower-left-half which takes a two dimensional array A, with size N rows and N columns as argument and prints the lower left-half.
2 3 1 5 0 7 1 5 3 1 e.g.,If A is 2 5 7 8 1 0 1 5 0 1 3 4 9 1 5 2 7 1 The output will be 2 5 7 0 1 5 0 3 4 9 1 5
Write a program to search for an ITEM linearly in array X[10].
The following array of integers is to be arranged in ascending order using the bubble sort technique:
26 21 20 23 29 17
Give the contents of the array at the end of each iteration. Do not write the algorithm.
Write a program to search for a given ITEM in a given array X[n] using linear search technique. If the ITEM is found, move it at the top of the array. If the ITEM is not found, insert it at the end of the array.