English

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,

Advertisements
Advertisements

Question

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
Code Writing
Advertisements

Solution

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
  Is there an error in this question or solution?
Chapter 8: Arrays - Sort & Search - Exercises [Page 199]

APPEARS IN

Rupa Pandit Computer Applications [English] Class 10 ICSE
Chapter 8 Arrays - Sort & Search
Exercises | Q 3. (iv) | Page 199
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×