Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views6 pages

Experiment 2 Aoa

Uploaded by

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

Experiment 2 Aoa

Uploaded by

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

ICOE/SE/AI&DS/2483115/Analysis of Algorithm Lab

EXPERIMENT NO.02
AIM: Experiment based on divide and conquers approach. (Merge sort,
Quick sort, Binary search)
THEORY:
Divide and Conquer Overview:
Divide and Conquer is a problem-solving approach that works by:
1. Dividing the problem into smaller sub-problems.
2. Conquering each sub-problem by solving them recursively.
3. Combining the solutions to form the final result.
This approach is widely used in designing efficient algorithms.
1. Merge Sort:

 Divide: Split the array into two halves.


 Conquer: Recursively sort both halves.
 Combine: Merge the two sorted halves into a single sorted array.

Time Complexity:

 Best, Average, Worst: O(n log n)


 Space Complexity: O(n)

1. Quick Sort:

Divide: Choose a pivot element and partition the array such that:

 Elements smaller than pivot go to the left,


 Elements greater go to the right.

Conquer: Recursively apply the above steps to left and right partitions.

Combine: No additional step required (in-place).

Time Complexity:

 Best, Average: O(n log n)


 Worst: O(n²) (when pivot is poorly chosen)
Space Complexity: O(log n) (due to recursion stack)

2. Binary Search:

Divide: Find the middle element of the sorted array.

Conquer:

 If the middle element equals the target, return it.


 If the target is smaller, repeat search in left half.
 If larger, search in right half.

Combine: No combination step (direct result).

Time Complexity: O(log n)

Space Complexity:
ICOE/SE/AI&DS/2483115/Analysis of Algorithm Lab
 Iterative: O(1)
 Recursive: O(log n)

ALGORITHM:

Binary Search Algorithm (Iterative)


Input:

A sorted array arr[] of n elements


An element x to search
Output:
Index of x if found, else -1

Algorithm Steps:
Initialize:
low ← 0
high ← n - 1
Repeat while low ≤ high:
mid ← low + (high - low) // 2
If arr[mid] = x:
Return mid (element found)
Else if arr[mid] < x:
low ← mid + 1 (search in right half)
Else:
high ← mid - 1 (search in left half)
If not found:
Return -1
Merge Sort Algorithm (Divide and Conquer)
Algorithm:
mergeSort(arr, left, right)
If left < right, then:
1.1. Find the middle point:
mid = (left + right) // 2A
1.2. Recursively sort first half:
mergeSort(arr, left, mid)
1.3. Recursively sort second half:
mergeSort(arr, mid + 1, right)
1.4. Merge the two halves:
merge(arr, left, mid, right)
merge(arr, left, mid, right)
Calculate sizes of two subarrays:
n1 = mid - left + 1
n2 = right - mid
Create temporary arrays:
L[0..n1-1] and R[0..n2-1]
Copy data into L[] and R[]
Merge the two arrays back into arr[left..right]
Copy any remaining elements of L[] and R[]
How Merge Sort Works (For Input [38, 27, 43, 10]):
Divide:
Split into [38, 27] and [43, 10]
Then [38], [27], [43], [10]
Conquer (sort each part):
Merge [38] and [27] → [27, 38]
Merge [43] and [10] → [10, 43]
Combine:
Merge [27, 38] and [10, 43] → [10, 27, 38, 43]
Output:
10 27 38 43
ICOE/SE/AI&DS/2483115/Analysis of Algorithm Lab
Quick Sort Algorithm (Divide and Conquer)
quickSort(arr, low, high)
1. If low < high:
pi = partition(arr, low, high)
Recursively sort the left half:
quickSort(arr, low, pi - 1)
Recursively sort the right half:
quickSort(arr, pi + 1, high
partition(arr, low, high)
1. Choose arr[high] as the pivot.
2. Initialize i = low - 1
3. For j from low to high - 1:
If arr[j] < pivot:
Increment i
Swap arr[i] and arr[j]
4. After loop ends, swap arr[i + 1] and arr[high] (put pivot in place)
5. Return i + 1 (pivot index)
How It Works (For input [10, 7, 8, 9, 1, 5]):
1. Choose pivot = 5
2. Partition the array → [1, 5, 8, 9, 7, 10]
Pivot 5 is now at correct index
Recursively sort:
Left part [1] — already sorted
Right part [8, 9, 7, 10]
Continue the same process until the whole array is sorted.
Output:
1 5 7 8 9 10
Time Complexity:
Best & Average Case: O(n log n)
Worst Case: O(n²) (when array is already sorted or all elements are equal)
Space Complexity: O(log n) (due to recursion)

CODE:
binarysearch.py

# Python3 code to implement iterative Binary


# Search.

# It returns location of x in given array arr


def binarySearch(arr, low, high, x):

while low <= high:

mid = low + (high - low) // 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:
low = mid + 1

# If x is smaller, ignore right half


else:
high = mid - 1

# If we reach here, then the element


# was not present
return -1
ICOE/SE/AI&DS/2483115/Analysis of Algorithm Lab
# Driver Code
if __name__ == '__main__':
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", result)
else:
print("Element is not present in array")

Mergesort.py
def merge(arr, left, mid, right):
n1 = mid - left + 1
n2 = right - mid

# Create temp arrays


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

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


for i in range(n1):
L[i] = arr[left + i]
for j in range(n2):
R[j] = arr[mid + 1 + j]

i=0
j=0
k = left

# Merge the temp arrays back


# into arr[left..right]
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
while j < n2:
arr[k] = R[j]
j += 1
k += 1

def mergeSort(arr, left, right):


if left < right:
mid = (left + right) // 2
ICOE/SE/AI&DS/2483115/Analysis of Algorithm Lab
mergeSort(arr, left, mid)
mergeSort(arr, mid + 1, right)
merge(arr, left, mid, right)

# Driver code
if __name__ == "__main__":
arr = [38, 27, 43, 10]

mergeSort(arr, 0, len(arr) - 1)
for i in arr:
print(i, end=" ")
print()

quicksort.py

# Partition function
def partition(arr, low, high):

# Choose the pivot


pivot = arr[high]

# Index of smaller element and indicates


# the right position of pivot found so far
i = low - 1

# Traverse arr[low..high] and move all smaller


# elements to the left side. Elements from low to
# i are smaller after every iteration
for j in range(low, high):
if arr[j] < pivot:
i += 1
swap(arr, i, j)

# Move pivot after smaller elements and


# return its position
swap(arr, i + 1, high)
return i + 1

# Swap function
def swap(arr, i, j):
arr[i], arr[j] = arr[j], arr[i]

# The QuickSort function implementation


def quickSort(arr, low, high):
if low < high:

# pi is the partition return index of pivot


pi = partition(arr, low, high)

# Recursion calls for smaller elements


# and greater or equals elements
quickSort(arr, low, pi - 1)
quickSort(arr, pi + 1, high)

# Main driver code


if __name__ == "__main__":
arr = [10, 7, 8, 9, 1, 5]
n = len(arr)

quickSort(arr, 0, n - 1)
ICOE/SE/AI&DS/2483115/Analysis of Algorithm Lab
for val in arr:
print(val, end=" ")

Conclusion:

Merge Sort, Quick Sort, and Binary Search effectively demonstrate the power of the Divide and Conquer
approach. They are efficient, structured, and form the foundation for solving complex problems in computer
science.

You might also like