DAA Project Part 1
DAA Project Part 1
of Algorithms part 1
Part a
1
Pseudocode:
MinMax(arr, low, high)
if p== q then
return (arr[p], arr[p])
else if high == low + 1 then
if arr[p] < arr[q] then
return (arr[p], arr[q])
else
return (arr[q], arr[p])
mid = (p + q) / 2
MinMax(arr, p, mid) = (leftMin, leftMax)
MinMax(arr, mid + 1, q) = (rightMin, rightMax)
min(leftMin, rightMin) = min_num
max(leftMax, rightMax) = max_num
return (min_num , max_num )
Implementation:
import java.util.Scanner;
if (p == q) {
result[0] = arr[p];
result[1] = arr[p];
return result;
}
int mid = (p + q) / 2;
System.out.println();
int[] result = MinMax(arr, 0, arr.length - 1);
In the brute force algorithm, we compare every element twice, once to find the minimum and
once to find the maximum. This increases the comparison rate by a constant factor of 2.
No of comparisons: 2(n-1)
The divide and conquer algorithm makes n-1 number of comparisons to accomplish the same
task.
Both brute-force and divide-and-conquer have linear time complexity O(n), but the constant
factor for the divide-and-conquer approach is smaller so it does the same work in fewer
comparisons.
Part b
1
Power(num, n)
if n = 0 then
return 1
if n is even then
c = Power(num, n / 2)
return c * c
else
c = Power(num, (n - 1) / 2)
return a * c * c
CODE
public class PowerCalculation {
public static long Power(long num, int n) {
if (n == 0) {
return 1;
}
long c = Power(num, n / 2);
if (n % 2 == 0) {
return c * c;
} else {
return num * c * c;
}
}
public static void main(String[] args) {
long num = 2;
int n = 15;
long answer = Power(num, n);
System.out.println(num + "^" + n + " = " + answer);
}
}
OUTPUT
2
Setting Up and Solving Recurrence Relation
3
The brute force algorithm would compute an by multiplying a , n number of times
which would lead to a time complexity of O(n). For example to compute 21024 we
would do: 2*2* 2*2… *2 (1024 times)
In comparison Divide and Conquer approach recursively divides the n by half.If the n is
even the division is n/2. If the n is odd the division is (n-1)/2. This is done recursively
till we reach a 0 or 1.
Part c
To find the total number of inversions in an array, we can use many approaches including an
algorithm that is similar to merge sort.
In my code, I have demonstrated how to use a self balancing binary search tree to find
inversions in an array in O(nlogn) time.
Pseudocode:
class Node{
value
left
right
countLeftNodes
}
//the insert function will count inversions for each element while inserting it in the BST
function insert(root, value){
if root is NULL:
root = create_new_node(value)
return root, 0
else:
root.right, inversions = insert(root.right, value)
inversions += (root.countLeftNodes + 1)
return root, inversions
}
function countInversions(arr){
root = NULL
total_inversions = 0
return total_inversions
}
Implementation:
class Node {
int value;
Node left;
Node right;
int leftCount;
Node(int value) {
this.value = value;
this.left = null;
this.right = null;
this.leftCount = 0;
}
}
int inversions = 0;
return totalInversions;
}
Output:
Part d
● Worst case time complexity for quickSort : O(n^2)
when the pivot divides the array in an unbalanced way, such as always choosing the smallest
or largest element as the pivot. In such cases, one partition has n−1 elements, and the other
has 0, leading to n recursive calls and a total of n^6 comparisons.
when the pivot divides the array into two equal parts. the array size is halved, and each level
processes n elements resulting in O(nlogn) comparisons
Part e
Example 5.5 (1)
1. Sort the array of numbers and divide the array into half
2. Recursively perform a linear scan of the array to find the closest pair in each half.
3. Compare the closest pairs found in both halves.
4. Additionally, check if the closest pair could lie between the largest element of the left
half and the smallest element of the right half
Sorting takes O(nlogn). After sorting, we perform a linear scan of the array to find the closest
pair, O(n). overall time complexity of algorithm is O(nlogn)
The divide and conquer guarantees a more efficient search for the closest pair compared to a
brute force O(n2). Whereas time complexity of O(nlogn) is optimal for this problem, given
that sorted array is needed .
Code
package CollectionFrameWork_gui;
public static void merge(double[] arr, int left, int mid, int right) {
int n1 = mid-left+1;
int n2 = right-mid;
int i = 0, j = 0, k =left;
arr[k++] = leftArray[i++]; }
while (i<n1) {
arr[k++] = leftArray[i++]; }
while (j <n2) {
arr[k++] = rightArray[j++]; }
if (right-left == 1) {
}
int mid = (left+right) /2;
double[] pair;
return pair;
mergeSort(numbers, 0, numbers.length-1);
}
Part f
ALGORITHM:
1. We first check the middle element A[n/2] and compare it with its neighbors A[n/2
- 1] and A[n/2 + 1].
2. If A[n/2 - 1] < A[n/2] < A[n/2 + 1], the peak must lie on the right half (
increasing array).
3. If A[n/2 - 1] > A[n/2] > A[n/2 + 1], the peak must lie on the left half (
decreasing array).
4. If A[n/2] is greater than both its neighbors, then A[n/2] is the peak.
IMPLEMENTATION:
public class FindPeak {
return mid;
}
Part g
Approach: We divide our input of prices array into sub array. There might be three possible
cases where we get the profit. In our solution, we calculate all three possibilities and then
compare them to get the maximum profit.
ALGORITHM
Input: An array of prices. The array index shows the day number.
1. If there are only 1 day then profit is 0. (start >=end)
2. Divide the array from mid into sets.
● Left Half: Start to Mid
● Rigth Half: Mid+1 to end
3. Recursively find the profit in the left half and the right half
4. Find the cross Profit which would be a minimum buy in the left half and a maximum
sell in the right half. Find min in the left half and max in the right half.
5. Compare the three possible profits and find the max. The possible profits are:
● Maximum Profit in Left Half
● Maximum Profit in Right Half
● Cross Profit
The maximum profit along with the corresponding day for buy and sell is returned.
6. Display the results.
CODE
public class StockProfit {
private static int MinIndex(int[] p, int start, int end) {
int minPrice = p[start];
int minIndex = start;
for (int i = start + 1; i <= end; i++) {
if (p[i] < minPrice) {
minPrice = p[i];
minIndex = i;
}
}
return minIndex;
}
private static int MaxIndex(int[] p, int start, int end) {
int maxPrice = p[start];
int maxIndex = start;
for (int i = start + 1; i <= end; i++) {
if (p[i] > maxPrice) {
maxPrice = p[i];
maxIndex = i;
}
}
return maxIndex;
}
public static int[] maximumProfitCalculation(int[] p, int i, int j) {
if (i >= j) {
return new int[]{0, -1, -1};
}
int mid = (i + j) / 2;
OUTPUT
Part h
Algorithm
package CollectionFrameWork_gui;
public class algoassignment {
public static int mergeAndCount(int[] arr, int left, int mid, int right)
{
int count = 0;
int i = 0, j = 0;
while (i <leftArr.length && j <rightArr.length) {
if (leftArr[i] > 2 * rightArr[j]) {
count += leftArr.length - i;
j++; }
else { i++; }
}
i = 0; j = 0;
int k = left;
while (i <leftArr.length) {
arr[k++] = leftArr[i++];
}
while (j <rightArr.length) {
arr[k++] = rightArr[j++];
}
return count;
}
count += mergeAndCount(arr,left,mid,right);
return count;
}
● Iterate through the list of bank cards to find a candidate that might represent a
majority.
● use the equivalence tester class to compare bank card objs
● After identifying a potential candidate having repeated usage , check how
many times this candidate appears in the list.
● confirm if it appears more than n/2.
boolean result =
FraudDetection.findMajorityEquivalent(cards);
System.out.println("is majority equivalent set? " + result);
}
}
class BankCard {
private String accountHolderName;
private String accountNumber;
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof BankCard other))
return false;
return accountNumber.equals(other.accountNumber);
}
@Override
public int hashCode() {
return accountNumber.hashCode();
}
}
class EquivalenceTester {
public boolean areEquivalent(BankCard card1, BankCard card2) {
return card1.equals(card2);
} }
class FraudDetection {
//candidate
for (BankCard card : cards) {
if (count == 0) {
candidate = card;
count = 1;
} else {
if (tester.areEquivalent(card, candidate)) {
count++;
} else {
count--;
}
}
}
count = 0;
for (BankCard card : cards) {
if (tester.areEquivalent(card, candidate)) {
count++; }
}
List<Line> visibleLines =
HiddenSurfaceRemoval.findVisibleLines(lines);
System.out.println("visible lines: y = ax + b");
for (Line line : visibleLines) {
System.out.println(line.a + "x + " + line.b);
}
}
}
class Line {
double a, b;
class Event {
double x;
Line line;
int type;
//1 for start, -1 for end
class HiddenSurfaceRemoval {
public static List<Line> findVisibleLines(List<Line> lines) {