0% found this document useful (0 votes)
77 views12 pages

Binary Search: Search A Sorted Array by Repeatedly Dividing The Search Interval in Half. Begin

Binary search is a fast search algorithm that works on sorted arrays or lists. It repeatedly divides the search interval in half and checks if the target value is in the upper or lower half. This process continues until the target is found or the interval is empty. Binary search ignores half of the remaining elements after each comparison, allowing it to find the target in logarithmic time compared to linear time for linear search. It works by comparing the target value to the middle element of the array/list, eliminating half of the elements from further search based on whether the target is less than or greater than the middle element.

Uploaded by

MIRTHIKA GK
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views12 pages

Binary Search: Search A Sorted Array by Repeatedly Dividing The Search Interval in Half. Begin

Binary search is a fast search algorithm that works on sorted arrays or lists. It repeatedly divides the search interval in half and checks if the target value is in the upper or lower half. This process continues until the target is found or the interval is empty. Binary search ignores half of the remaining elements after each comparison, allowing it to find the target in logarithmic time compared to linear time for linear search. It works by comparing the target value to the middle element of the array/list, eliminating half of the elements from further search based on whether the target is less than or greater than the middle element.

Uploaded by

MIRTHIKA GK
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Binary Search: Search a sorted array by repeatedly dividing the search interval in half.

Begin
with an interval covering the whole array. If the value of the search key is less than the item in
the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper
half. Repeatedly check until the value is found or the interval is empty.

We basically ignore half of the elements just after one comparison.


1. Compare x with the middle element.
2. If x matches with middle element, we return the mid index.
3. Else If x is greater than the mid element, then x can only lie in right half subarray
after the mid element. So we recur for right half.
4. Else (x is smaller) recur for the left half.

# Python Program for recursive binary search.

# Returns index of x in arr if present, else -1


def binarySearch (arr, l, r, x):

# Check base case


if r >= l:

mid = l + (r - l)/2

# If element is present at the middle itself


if arr[mid] == x:
return mid

# If element is smaller than mid, then it


# can only be present in left subarray
elif arr[mid] > x:
return binarySearch(arr, l, mid-1, x)

# Else the element can only be present


# in right subarray
else:
return binarySearch(arr, mid + 1, r, x)

else:
# Element is not present in the array
return -1

# Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 10

# Function call
result = binarySearch(arr, 0, len(arr)-1, x)

if result != -1:
print "Element is present at index % d" % result
else:
print "Element is not present in array"
Output :
Element is present at index 3

# Python code to implement iterative Binary


# Search.

# It returns location of x in given array arr


# if present, else returns -1
def binarySearch(arr, l, r, x):

while l <= r:

mid = l + (r - l)/2;

# Check if x is present at mid


if arr[mid] == x:
return mid

# If x is greater, ignore left half


elif arr[mid] < x:
l = mid + 1

# If x is smaller, ignore right half


else:
r = mid - 1

# If we reach here, then the element


# was not present
return -1

# Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 10

# Function call
result = binarySearch(arr, 0, len(arr)-1, x)

if result != -1:
print "Element is present at index % d" % result
else:
print "Element is not present in array
Binary search is implemented using following steps...

 Step 1 - Read the search element from the user.


 Step 2 - Find the middle element in the sorted list.
 Step 3 - Compare the search element with the middle element in the sorted list.
 Step 4 - If both are matched, then display "Given element is found!!!" and terminate the
function.
 Step 5 - If both are not matched, then check whether the search element is smaller or larger
than the middle element.
 Step 6 - If the search element is smaller than middle element, repeat steps 2, 3, 4 and 5 for
the left sublist of the middle element.
 Step 7 - If the search element is larger than middle element, repeat steps 2, 3, 4 and 5 for the
right sublist of the middle element.
 Step 8 - Repeat the same process until we find the search element in the list or until sublist
contains only one element.
 Step 9 - If that element also doesn't match with the search element, then display
"Element is not found in the list!!!" and terminate the function.
Linear search is a very simple search algorithm. In this type of search, a
sequential search is made over all items one by one. Every item is checked and
if a match is found then that particular item is returned, otherwise the search
continues till the end of the data collection.

Pseudocode
procedure linear_search (list, value)

for each item in the list

if match item == value

return the item's location

end if

end for

end procedure

xamples :
Input : arr[] = {10, 20, 80, 30, 60, 50,
110, 100, 130, 170}
x = 110;
Output : 6
Element x is present at index 6

Input : arr[] = {10, 20, 80, 30, 60, 50,


110, 100, 130, 170}
x = 175;
Output : -1
Element x is not present in arr[].
# Python3 code to linearly search x in arr[].
# If x is present then return its location,
# otherwise return -1

def search(arr, n, x):

for i in range (0, n):


if (arr[i] == x):
return i;
return -1;

# Driver Code
arr = [ 2, 3, 4, 10, 40 ];
x = 10;
n = len(arr);
result = search(arr, n, x)
if(result == -1):
print("Element is not present in array")
else:
print("Element is present at index", result);

Linear search is implemented using following steps...

 Step 1 - Read the search element from the user.


 Step 2 - Compare the search element with the first element in the list.
 Step 3 - If both are matched, then display "Given element is found!!!" and terminate the
function
 Step 4 - If both are not matched, then compare search element with the next element in the
list.
 Step 5 - Repeat steps 3 and 4 until search element is compared with last element in the list.
 Step 6 - If last element in the list also doesn't match, then display "Element is not found!!!" and
terminate the function.

Example
Consider the following list of elements and the element to be searched...


Insertion sort is based on the idea that one element from the input elements is consumed in each
iteration to find its correct position i.e, the position to which it belongs in a sorted array.

It iterates the input elements by growing the sorted array at each iteration. It compares the current
element with the largest value in the sorted array. If the current element is greater, then it leaves the
element in its place and moves on to the next element else it finds its correct position in the sorted
array and moves it to that position. This is done by shifting all the elements, which are larger than
the current element, in the sorted array to one position ahead

Step by Step Process


The insertion sort algorithm is performed using following steps...

 Step 1 - Assume that first element in the list is in sorted portion and all the remaining elements
are in unsorted portion.
 Step 2: Take first element from the unsorted portion and insert that element into the sorted
portion in the order specified.
 Step 3: Repeat the above process until all the elements from the unsorted portion are moved
into the sorted portion.
 Take array A[]=[7,4,5,2].

Since 7 is the first


element has no other element to be compared with, it remains at its position. Now when on moving
towards 4, 7 is the largest element in the sorted list and greater than 4. So, move 4 to its correct
position i.e. before 7. Similarly with 5, as 7 (largest element in the sorted list) is greater than 5, we
will move 5 to its correct position. Finally for 2, all the elements on the left side of 2 (sorted list) are
moved one position forward as all are greater than 2 and then 2 is placed in the first position. Finally,
the given array will result in a sorted array.

 nother Example:
12, 11, 13, 5, 6
 Let us loop for i = 1 (second element of the array) to 4 (last element of the array)
 i = 1. Since 11 is smaller than 12, move 12 and insert 11 before 12
11, 12, 13, 5, 6
 i = 2. 13 will remain at its position as all elements in A[0..I-1] are smaller than 13
11, 12, 13, 5, 6
 i = 3. 5 will move to the beginning and all other elements from 11 to 13 will move
one position ahead of their current position.
5, 11, 12, 13, 6
 i = 4. 6 will move to position after 5, and elements from 11 to 13 will move one
position ahead of their current position.
5, 6, 11, 12, 13

# Python program for implementation of Insertion Sort

# Function to do insertion sort


def insertionSort(arr):

# Traverse through 1 to len(arr)


for i in range(1, len(arr)):

key = arr[i]

# Move elements of arr[0..i-1], that are


# greater than key, to one position ahead
# of their current position
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key

# Driver code to test above


arr = [12, 11, 13, 5, 6]
insertionSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i])

# This code is contributed by Mohit Kumra


Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-
based algorithm in which each pair of adjacent elements is compared and the
elements are swapped if they are not in order. This algorithm is not suitable for
large data sets as its average and worst case complexity are of Ο(n2) where n is
the number of items.

Following are the steps involved in bubble sort(for sorting a given array in ascending order):

1. Starting with the first element(index = 0), compare the current element with the next
element of the array.
2. If the current element is greater than the next element of the array, swap them.
3. If the current element is less than the next element, move to the next element. Repeat
Step 1.

xample:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and
swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5),
algorithm does not swap them.
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The
algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

# Python program for implementation of Bubble Sort

def bubbleSort(arr):
n = len(arr)

# Traverse through all array elements


for i in range(n):

# Last i elements are already in place


for j in range(0, n-i-1):

# traverse the array from 0 to n-i-1


# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]

# Driver code to test above


arr = [64, 34, 25, 12, 22, 11, 90]

bubbleSort(arr)

print ("Sorted array is:")


for i in range(len(arr)):
print ("%d" %arr[i]),

Quick sort is based on the divide-and-conquer approach based on the idea of choosing one element
as a pivot element and partitioning the array around it such that: Left side of pivot contains all the
elements that are less than the pivot element Right side contains all elements greater than the pivotIt
reduces the space complexity and removes the use of the auxiliary array that is used in merge sort.
Selecting a random pivot in an array results in an improved time complexity in most of the cases.
Step by Step Process
In Quick sort algorithm, partitioning of the list is performed using following steps...

 Step 1 - Consider the first element of the list as pivot (i.e., Element at first position in the list).
 Step 2 - Define two variables i and j. Set i and j to first and last elements of the list respectively.
 Step 3 - Increment i until list[i] > pivot then stop.
 Step 4 - Decrement j until list[j] < pivot then stop.
 Step 5 - If i < j then exchange list[i] and list[j].
 Step 6 - Repeat steps 3,4 & 5 until i > j.
 Step 7 - Exchange the pivot element with list[j] element.
 Python program for implementation of Quicksort Sort

 # This function takes last element as pivot, places
 # the pivot element at its correct position in sorted
 # array, and places all smaller (smaller than pivot)
 # to left of pivot and all greater elements to right
 # of pivot
 def partition(arr,low,high):
 i = ( low-1 ) # index of smaller element
 pivot = arr[high] # pivot

 for j in range(low , high):

 # If current element is smaller than or
 # equal to pivot
 if arr[j] <= pivot:

 # increment index of smaller element
 i = i+1
 arr[i],arr[j] = arr[j],arr[i]

 arr[i+1],arr[high] = arr[high],arr[i+1]
 return ( i+1 )

 # The main function that implements QuickSort
 # arr[] --> Array to be sorted,
 # low --> Starting index,
 # high --> Ending index

 # Function to do Quick sort
 def quickSort(arr,low,high):
 if low < high:

 # pi is partitioning index, arr[p] is now
 # at right place
 pi = partition(arr,low,high)

 # Separately sort elements before
 # partition and after partition
 quickSort(arr, low, pi-1)
 quickSort(arr, pi+1, high)

 # Driver code to test above
 arr = [10, 7, 8, 9, 1, 5]
 n = len(arr)
 quickSort(arr,0,n-1)
 print ("Sorted array is:")
 for i in range(n):
 print ("%d" %arr[i]),

 # This code is contributed by Mohit Kumra

You might also like