ADS Lab Experiments
ADS Lab Experiments
# 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.
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
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
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
4
print("Sorted array is:")
for i in range(n):
print("%d" % arr[i])
Expected Output:
1
5
7
8
9
10