Advertisements
Advertisements
प्रश्न
The following code may contain some errors. Identify the errors, modify the program by underlining the changes made, and write the aim of the program.
int SA[ ] = {79, 58, 42, 61, 79, 66, 34, 62, 94, 73};
int n = SA.length;
void fnBinarySearch(int val)
{
while(min <= max)
{
mid = low + high/2;
System.out.print("\n Element at mid " + mid + "“ IS " + SA[mid]);
if(SA[mid]=val)
{
found = true;
break;
}
else if(SA [mid] < val)
{
high = mid -1;
}
else
{
low = mid + 1;
}
}
if(found=true)
System.out.print("\n Element" + val + “ IS Present.");
else
System.out.print("\n Element " + val + " IS NOT Present.");
} //closing binary searchकोड लेखन
Advertisements
उत्तर
Logical Error: Calculation of mid
import java.util.*;
class c12
{
int SA[] = {79, 58, 42, 61, 79, 66, 34, 62, 94, 73};
int n = SA.length;
void fnBinarySearch(int val)
{
int low = 0, high =n - 1; boolean found = false;
while(low <= high)
{
int mid = (low + high)/2;
System.out.print("\n Element at mid " + mid + IS " + SA [ mid ]);
if(SA[mid] =val)
{
found = true;
break;
}
else if(SA [mid] < val)
{
high = mid -1;
}
else
{
low = mid + 1;
}
}
if(found =true)
System.out.print("\n Element " + val + " IS Present.");
else
System.out.print("\n Element " + val + " IS NOT Present.");
} //closing binary search
}
Output:
Element to search = 69...//input by the user
Element at mid 4 IS 79
Element at mid 7 IS 62
Element at mid 5 IS 66
Element 69 IS NOT Present.
Aim: The aim of the program is to search for an element in an array using binary search.
shaalaa.com
क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
अध्याय 8: Arrays - Sort & Search - Exercises [पृष्ठ १९९]
