Shortest possible depth of a leaf in decision tree (comparison sorting algorithm)

The absolute best case happens when we just check every element and see that the data’s already sorted. This will result in n-1 comparisons and thus the leaf will have a depth of n-1. Practically, this happens for insertion sort (which isn’t all that good otherwise though). Does it change depending on the algorithm? Absolutely. The best case of an … Read more

Trying to understand max heapify

Here’s what MAX-HEAPIFY does: Given a node at index i whose left and right subtrees are max-heaps, MAX-HEAPIFY moves the node at i down the max-heap until it no longer violates the max-heap property (that is, the node is not smaller than its children). The longest path that a node can take before it is in the proper position … Read more

When should I use Kruskal as opposed to Prim (and vice versa)?

Use Prim’s algorithm when you have a graph with lots of edges. For a graph with V vertices E edges, Kruskal’s algorithm runs in O(E log V) time and Prim’s algorithm can run in O(E + V log V) amortized time, if you use a Fibonacci Heap. Prim’s algorithm is significantly faster in the limit when you’ve got a really dense graph with many … Read more

longest increasing subsequence(O(nlogn))

Let’s first look at the n^2 algorithm: Now the improvement happens at the second loop, basically, you can improve the speed by using binary search. Besides the array dp[], let’s have another array c[], c is pretty special, c[i] means: the minimum value of the last element of the longest increasing sequence whose length is … Read more

Is Quicksort in-place or not?

Intro to Algorithms from MIT Press qualifies QuickSort as in-place – it sorts the elements within the array with at most a constant amount of them outside the array at any given time. At the end of the day, people will always have differing opinions (is Top-Down Memoization considered Dynamic Programming? Not to some “classical” folks), side with who you … Read more

Performing Breadth First Search recursively

(I’m assuming that this is just some kind of thought exercise, or even a trick homework/interview question, but I suppose I could imagine some bizarre scenario where you’re not allowed any heap space for some reason [some really bad custom memory manager? some bizarre runtime/OS issues?] while you still have access to the stack…) Breadth-first … Read more

Best Case for Bubble Sort

I want to know what will be the best case for a bubble sort ? There may be a case wherein there may be no swapping for the say last 2 passes for example. I’m doing my program in C language. Suppose i have an array of 5 elements and i give the elements as … Read more