Home Page class 12 @ Python

CBSE Class 12 : Data Structures

Introduction to Data Structures

CBSE Class 12 : Searching

Creation And Traversal
What is Searching?
Linear/Sequential Search
Binary Search
Insertion Of Element
Deletion Of Element

CBSE Class 12 : Sorting

What is sorting?
Bubble Sort
Selection Sort
Insertion Sort

CBSE Class 12 : Stacks

Applications of Stacks
Implementation of Stacks

CBSE Class 12 : Queues

Applications Of Queues
Implementation of Queues

Class 12: Data Structures Searching 6

Write a python script to search an element with in a list using Binary Search.(Create a user defined list)

def binary_search(arr, x): 
    low = 0
    high = len(arr) - 1
    mid = 0
    while low <= high: 
        mid = (high + low) // 2
        # Check if x is present at mid 
        if arr[mid] < x: 
            low = mid + 1
        # If x is greater, ignore left half 
        elif arr[mid] > x: 
            high = mid - 1
        # If x is smaller, ignore right half 
            return mid 
    # If we reach here, then the element was not present 
    return -1
#-- main --
# create a user defined list
while True:
    a=int(input("Enter the element to add "))
    ch=input("Like to cont (y/n) ")
    if(ch=="y" or ch=="Y"):

#to display the list
#to sort the elements of the list arr
#condition for binary search is elements should be sorted
print("Sorted list")
x=int(input("Enter the element to search "))
# Function call 
result = binary_search(arr, x) 
if result != -1: 
    print("Element is present at index", str(result)," position = ",str(result+1)) 
    print("Element is not present in array") 


Enter the element to add 10
Like to cont (y/n) y
Enter the element to add 25
Like to cont (y/n) y
Enter the element to add 96
Like to cont (y/n) y
Enter the element to add 4
Like to cont (y/n) y
Enter the element to add 65
Like to cont (y/n) n
[10, 25, 96, 4, 65]
Sorted list
[4, 10, 25, 65, 96]
Enter the element to search 25
Element is present at index 2  position =  3