0% found this document useful (0 votes)
2 views2 pages

Algorithm Answers

The document discusses various algorithms and their time complexities, including recursive binary search, Johnson-Trotter for permutations, and the power function using divide and conquer. It also covers Horspool's algorithm for pattern matching, Floyd-Warshall for all-pairs shortest paths, Kruskal's for minimum weight spanning trees, and the knapsack problem using dynamic programming. Additionally, it contrasts divide and conquer with dynamic programming in terms of efficiency and complexity.
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)
2 views2 pages

Algorithm Answers

The document discusses various algorithms and their time complexities, including recursive binary search, Johnson-Trotter for permutations, and the power function using divide and conquer. It also covers Horspool's algorithm for pattern matching, Floyd-Warshall for all-pairs shortest paths, Kruskal's for minimum weight spanning trees, and the knapsack problem using dynamic programming. Additionally, it contrasts divide and conquer with dynamic programming in terms of efficiency and complexity.
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/ 2

13.

Time Complexity of Recursive Binary Search

Method 1 (Recurrence): T(n) = T(n/2) + c -> O(log n)

Method 2 (Iterative Approximation): Each call halves the array -> O(log n)

14. Johnson-Trotter Algorithm (Permutations of 4)

Steps:

1. Start with [1,2,3,4], assign directions

2. Find largest mobile

3. Swap and reverse directions

Example: [1,2,3,4] -> [1,2,4,3] -> [1,4,2,3] -> ...

15. Power A^n using Divide and Conquer

Pseudocode:

int power(int A, int n) {

if(n==0) return 1;

int half = power(A, n/2);

return (n%2==0) ? half*half : A*half*half;

Time Complexity: O(log n)

16. Horspool's Algorithm

Time: Best O(n/m), Worst O(mn)

Space: O() for shift table

Example: Pattern 'abc' in text 'abacbcababc'

17. All-Pairs Shortest Path (Floyd-Warshall)


Initialize dist[i][j] = weight or INF

For k in V: dist[i][j] = min(dist[i][j], dist[i][k]+dist[k][j])

Time Complexity: O(V^3)

18. Minimum Weight Spanning Tree (Kruskal's)

Steps:

1. Sort edges by weight

2. Pick smallest edge avoiding cycles

3. Stop at V1 edges

Example: Start with (1,2)=1, (6,3)=2, ...

19. Knapsack Problem (M=40, weights=[20,25,10,15], profits=[20,40,35,45])

Use DP: dp[i][w] = max(dp[i-1][w], dp[i-1][w-wt[i]] + profit[i])

Result at dp[4][40]

20. Divide and Conquer vs Dynamic Programming

Divide and Conquer: +Simple, -Recomputes

Dynamic Programming: +Efficient, -High space, complex

You might also like