0% found this document useful (0 votes)
69 views5 pages

ADS Lab Experiments

The document describes how to implement binary search and merge sort for a given list of integers. It provides code for a binary search function that returns the index of an element if found, otherwise returns -1. It also provides code to implement merge sort using a merge function to combine two sorted halves. The merge sort code includes driver code to test sorting an sample array.

Uploaded by

kuruvakavyapriya
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)
69 views5 pages

ADS Lab Experiments

The document describes how to implement binary search and merge sort for a given list of integers. It provides code for a binary search function that returns the index of an element if found, otherwise returns -1. It also provides code to implement merge sort using a merge function to combine two sorted halves. The merge sort code includes driver code to test sorting an sample array.

Uploaded by

kuruvakavyapriya
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/ 5

Write a program to perform Binary Search for a given set of integers

# Iterative Binary Search Function


# It returns index of x in given array arr if present,
# else returns -1

def binary_search(arr, x):


low = 0
high = len(arr) - 1
mid = 0

while low <= high:

mid = (high + low) // 2

# If x is greater, ignore left half


if arr[mid] < x:
low = mid + 1

# If x is smaller, ignore right half


elif arr[mid] > x:
high = mid - 1

# means x is present at mid


else:
return mid

# If we reach here, then the element was not present


return -1

# Test array
arr = [ 2, 3, 4, 10, 40]
x = int(input(“enter element in the given arr variable : “)

# Function call
result = binary_search(arr, x)

if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in the given array")

Expected Input – 1:
Enter element in the given arr variable : 2
Expected Output - 1:
Element is present at index 0
Expected Input – 2:
Enter element in the given arr variable : 45
Expected Output - 1:
Element is not present in the given array

1
Write a program to implement Merge Sort for a given list of integer values

Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls
itself for the two halves and then merges the two sorted halves. The merge() function is
used for merging two halves. The merge(arr, l, m, r) is key process that assumes that
arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one.

# Python program for implementation of MergeSort

# Merges two subarrays of arr[].


# First subarray is arr[l..m]
# Second subarray is arr[m+1..r]

def merge(arr, l, m, r):


n1 = m - l + 1
n2 = r - m

# create temp arrays


L = [0] * (n1)
R = [0] * (n2)

# Copy data to temp arrays L[] and R[]


for i in range(0, n1):
L[i] = arr[l + i]

for j in range(0, n2):


R[j] = arr[m + 1 + j]

# Merge the temp arrays back into arr[l..r]


i = 0 # Initial index of first subarray
j = 0 # Initial index of second subarray
k = l # Initial index of merged subarray

while i < n1 and j < n2:


if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1

# Copy the remaining elements of L[], if there are any


while i < n1:
arr[k] = L[i]
i += 1
k += 1
# Copy the remaining elements of R[], if there are any

2
while j < n2:
arr[k] = R[j]
j += 1
k += 1

# l is for left index and r is right index of the sub-array of arr to be sorted

def mergeSort(arr, l, r):


if l < r:

# Same as (l+r)//2, but avoids overflow for large l and h


m = l+(r-l)//2

# Sort first and second halves


mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)

# Driver code to test above


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

mergeSort(arr, 0, n-1)
print("\n\nSorted array is")
for i in range(n):
print("%d" % arr[i],end=" ")

Expected Output:

Given array is

12, 11, 13, 5, 6, 7

Sorted array is

5, 6, 7, 11, 12, 13

Write a program to implement Merge Sort for a given list of integer values

Like Merge Sort, QuickSort is a Divide and Conquer algorithm. It picks an element as pivot
and partitions the given array around the picked pivot. There are many different versions of
quickSort that pick pivot in different ways.
1. Always pick first element as pivot.
2. Always pick last element as pivot (implemented below)
3. Pick a random element as pivot.

3
4. Pick median as pivot.
The key process in quickSort is partition(). Target of partitions is, given an array and an
element x of array as pivot, put x at its correct position in sorted array and put all smaller
elements (smaller than x) before x, and put all greater elements (greater than x) after x. All
this should be done in linear time.

# 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 len(arr) == 1:
return arr
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)

4
print("Sorted array is:")
for i in range(n):
print("%d" % arr[i])

Expected Output:

Sorted array is:

1
5
7
8
9
10

You might also like