You are on page 1of 6

Algorithms and Problem-Solving Lab (15B17CI471)

EVEN 2022 Week -3 (31 Jan – 6 Feb 2023)


Practice Assignment Topic: Divide and Conquer

Q.1.Cubic integer root x of n is largest number x such that x3<=n. Find the value of x
given n using divide and conquer approach. Also analyse the complexity.
Ans) //.Cubic integer root x of n is largest number x such that x3<=n. Find the value of x given n
using divide
//and conquer approach. Also analyse the complexity.

#include<iostream>
#include<cmath>
using namespace std;

void cubic(int n)
{
float m1;
m1=n/2;
int m2;
m2=ceil(m1);

//cout<<m2;
if((m2*m2*m2) <= n)
{
cout<<m2;
}
else{
cubic(m2);
}
}

int main()
{
cout<<"Enter the number"<<endl;
int n;
cin>>n;
cubic(n);

}
Q2. Given a sorted array in which all elements appear twice (one after one) and one
element appears only once. Find that element in O(log n) complexity. Example: Input:
arr[] = {1, 1, 3, 3, 4, 5, 5, 7, 7, 8, 8} Output: 4
Input: arr[] = {1, 1, 3, 3, 4, 4, 5, 5, 7, 7, 8} Output: 8
Ans) #include <iostream>
using namespace std;

void search(int arr[], int low, int high)


{

if (low > high)


return;

if (low == high) {
cout << "The single element is " << arr[low];
return;
}
int mid = (low + high) / 2;
if (mid % 2 == 0) {
if (arr[mid] == arr[mid + 1])
search(arr, mid + 2, high);
else
search(arr, low, mid);
}

// If mid is odd
else {
if (arr[mid] == arr[mid - 1])
search(arr, mid + 1, high);
else
search(arr, low, mid - 1);
}
}

int main()
{
int arr1[] = {1, 1, 3, 3, 4, 5, 5, 7, 7, 8, 8};
int arr2[]={1, 1, 3, 3, 4, 4, 5, 5, 7, 7, 8};
int size = sizeof(arr1) / sizeof(arr1[0]);
//int len = sizeof(arr2) / sizeof(arr2[0]);
if(size%2 == 0)
{
cout<<"single element does not exist"<<endl;
}
else{
search(arr1, 0, size - 1);
cout<<endl;}
//search(arr2, 0, len - 1);

return 0;
}

Q3. List of points have been given on 2D Plane. Calculate K closest points to the origin
(0,0) (Consider euclidean distance to find the distance between two points). Write a code
to return the answer in any order. The solution is guaranteed to be unique.
Ans) def closestPoints(points, k):
# Create an empty list of distance
distances = []

# Iterate through the points


for point in points:
# Calculate the distance between the point and origin (0, 0)
distance = (point[0] ** 2 + point[1] ** 2) ** 0.5

# Append the distance to the distances list


distances.append((distance, point))

# Sort the distances list


distances.sort(key=lambda x: x[0])

# Return the k closest points


return [x[1] for x in distances[:k]]

# Test
points = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12)]
k=3

print(closestPoints(points, k))
# Output: [(1, 2), (3, 4), (5, 6)]
Q4. Let there be an array of N random elements. We need to sort this array in ascending
order. If n is very large (i.e. N= 1,00,000) then Quicksort may be considered as the fastest
algorithm to sort this array. However, we can further optimize its performance by
hybridizing it with insertion sort. Therefore, if n is small (i.e. N<= 10) then we apply
insertion sort to the array otherwise Quick Sort is applied. Implement the above
discussed hybridized Quick Sort and compare the running time of normal Quick sort and
hybridized quick sort. Run each type of sorting 10 times on a random set of inputs and
compare the average time returned by these algorithms.
Ans) // Hybridized Quick Sort implementation
// Function to implement QuickSort
// arr[] --> Array to be sorted,
// l --> Starting index,
// h --> Ending index
function quickSort(arr, l, h)
{
// If the subarray size is small enough,
// apply insertion sort
if (h - l <= 10) {
insertionSort(arr, l, h);
return;
}

// Create an auxiliary stack


var stack = [];

// initialize top of stack


var top = -1;

// push initial values of l and h to stack


stack[++top] = l;
stack[++top] = h;

// Keep popping from stack while is not empty


while (top >= 0) {
// Pop h and l
h = stack[top--];
l = stack[top--];

// Set pivot element at its correct position


// in sorted array
Q5. Consider a sorted array A of n elements. The array A may have repetitive/duplicate
elements. For a given target element T, design and implement an efficient algorithm to
find T’s first and last occurrence in the array A. Also print the message if an element was
not present in the array. For Example, Input: arr = [2, 5, 5, 5, 6, 6, 8, 9, 9, 9] target = 5
Output: The first occurrence of element 5 is located at index 1 The last occurrence of
element 5 is located at index 3 Input: arr = [2, 5, 5, 5, 6, 6, 8, 9, 9, 9] target = 4 Output:
Element not found in the array
Ans) The algorithm can be designed using binary search. First, we use binary search to find the
index of the first occurrence of the target element T in the array A. Then, we use binary search
again to find the index of the last occurrence of T by searching in the subarray that starts from
the index found in the first search and ends at the end of the array. The algorithm has a time
complexity of O(log n) for both binary searches.
def binary_search_first(arr, low, high, target):
if high >= low:
mid = (high + low) // 2
if (mid == 0 or target > arr[mid-1]) and arr[mid] == target:
return mid
elif target > arr[mid]:
return binary_search_first(arr, (mid + 1), high, target)
else:
return binary_search_first(arr, low, (mid -1), target)
return -1

def binary_search_last(arr, low, high, target):


if high >= low:
mid = (high + low) // 2
if (mid == len(arr)-1 or target < arr[mid+1]) and arr[mid] == target:
return mid
elif target < arr[mid]:
return binary_search_last(arr, low, (mid -1), target)
else:
return binary_search_last(arr, (mid + 1), high, target)
return -1

def first_last_occurrence(arr, target):


n = len(arr)
first = binary_search_first(arr, 0, n-1, target)
if first != -1:
last = binary_search_last(arr, first, n-1, target)
print("The first occurrence of element", target, "is located at index", first)
print("The last occurrence of element", target, "is located at index", last)
else:
print("Element not found in the array")
arr = [2, 5, 5, 5, 6, 6, 8, 9, 9, 9]
target = 5
first_last_occurrence(arr, target)

You might also like