Skip to main content

Binary Search

Binary Search is a method of searching an element in a sorted list of items. It follows the divide and conquer approach. The list is divided into two halves. The key(element to be searched) is compared with the middle element of list. If the element is found the index is returned, else, the element is searched in either of the sub-list until found or the last sub-list(only one element remaining) is visited. 

Illustration:


Algorithm:

  1. Initialize the sorted list, set low=0 and high=length(list)-1
  2. Set mid=low+(high-low)//2
  3. Compare key with element at mid
  4. If list[mid]==key, then return mid
  5. Else if list[mid]>key, then low=low and high=mid-1
  6. Repeat from 2 till list[mid]=key, else return= -1
  7. Else low=mid+1 and high=high
  8. Repeat from 2  till list[mid]=key, else return=-1
  9. If return = -1, then print "Not found"
  10. End

Time Complexity:

  • Worst Case: O(log n) 
  • Average Case: O(log n)
  • Best Case: O(1)

Space Complexity: O(1)

Program for Binary Search


Popular posts from this blog

Coding Problem: Area of Circle

 Write a program to print the area of a circle of given radius ' r ' up to 2 decimal places. Code: Output:

Image to Pencil Sketch using Python and OpenCV

In this post, we will go through a program to get a pencil sketch from an image using python and OpenCV.  Step 1:  To use OpenCV, import the library. Step 2: Read the Image. Step 3: Create a new image by converting the original image to grayscale. Step 4: Invert the grayscale image. We can invert images simply by subtracting from 255, as grayscale images are 8 bit images or have a maximum of 256 tones. Step 5: Blur the inverted image using GaussianBlur  method in OpenCV library and invert the blurred image.  Step 6: Divide the grayscale values of the image by the values of image received from step-5 ( Note: We inverted the grayscale image and we blurred this image and then again inverted it ). Diving an image from its smoothened form will highlight the edges and we get the image like Pencil Sketch. Steps Illustration: Code: Execution Output:

Coding Problem: Based on Caesar Cypher

This a coding problem based on Caesar Cypher(or Cipher). Caesar Cipher Technique is a simple and easy method of encryption. It is a simple type of substitution cipher in which each letter of plain text is replaced by a letter with some fixed number of positions down with alphabet. This is used in a way: Given: a=z  b=y ............ z=a For example: Input: abc Output should Be:  zyx Code: