About bubble sort vs merge sort

It’s a trick question. If you just want the maximum, (or indeed, the kth value for any k, which includes finding the median), there’s a perfectly good O(n) algorithm. Sorting is a waste of time. That’s what they want to hear. As you say, the algorithm for maximum is really trivial. To ace a question like this, you …

Read more

Minesweeper solving algorithm

I am pretty sure most of you know about the minesweeper game. I wanted to code (in C#) my own minesweeper game and was looking for some input as to what would be a good algorithm for that game. I have been browsing over the web for quite some time now but could not find …

Read more

Sorting an array in C?

In C, you can use the built in qsort command: see: http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/ To answer the second part of your question: an optimal (comparison based) sorting algorithm is one that runs with O(n log(n)) comparisons. There are several that have this property (including quick sort, merge sort, heap sort, etc.), but which one to use depends on your use …

Read more

Are there any real O(n^n) algorithms?

What you have coded in your example is very similar to a depth first search. So, that’s one answer. A depth first search algorithm without any special characteristics ( like re-convergent paths that can be optimized out ), should be n^n. This is actually not a contrived example. Chess programs operate on the same algorithm. …

Read more

Finding all possible combinations of numbers to reach a given sum

This problem can be solved with a recursive combinations of all possible sums filtering out those that reach the target. Here is the algorithm in Python: This type of algorithms are very well explained in the following Stanford’s Abstract Programming lecture – this video is very recommendable to understand how recursion works to generate permutations of solutions. …

Read more

Difference between O(n) and O(log(n)) – which is better and what exactly is O(log(n))?

It means that the thing in question (usually running time) scales in a manner that is consistent with the logarithm of its input size. Big-O notation doesn’t mean an exact equation, but rather a bound. For instance, the output of the following functions is all O(n): Because as you increase x, their outputs all increase linearly – if there’s …

Read more

How are the following functions O(N^3)?

Do you know, f(n) = O(g(n)) implies f(n) <= constant* g(n), right? In other words, it means, when you plot the graph of f(n) and g(n) then after some value of, g(n) will always be more than f(n). Here g(n) is N^3 and remaining comes in f(n). Now, N^3 is always >= options a, b, c. hence answer id D 🙂 Edit: Following statements are true, n=O(n) n=O(n^2) n=O(n^3) But only n = O(n) is tight upper bound and that is what …

Read more