Friday, February 1, 2019

Searching

  • Problem Description

    Given a sorted array of n elements, write a program using binary search to search a given element x in list

    Input:
    Number of elements, elements in sorted order and finally the element to be searched in the array.

    Output:
    The location where the element is found
  • CODING ARENA
  • a=int(input())
    ans=0
    lis=[]
    for i in range(a):
        x=int(input())
        lis.append(x)
    k=int(input())
    for i in range(a):
            if(k==lis[i]):
                ans=i+1
                break
    if(ans==0):
        print(k,"not found")
    else:
        print(k,"found at location",ans)
  • Test Case 1

    Input (stdin)
    5
    
    2
    
    4
    
    10
    
    20
    
    44
    
    10
    
    
    Expected Output
    10 found at location 3
  • Test Case 2

    Input (stdin)
    7
    
    5
    
    10
    
    22
    
    67
    
    78
    
    79 
    
    99
    
    4
    
    
    Expected Output
    4 not found

No comments:

Post a Comment