Best way to randomize an array with .NET

If you’re on .NET 3.5, you can use the following IEnumerable coolness: Edit: and here’s the corresponding VB.NET code: Second edit, in response to remarks that System.Random “isn’t threadsafe” and “only suitable for toy apps” due to returning a time-based sequence: as used in my example, Random() is perfectly thread-safe, unless you’re allowing the routine … Read more

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

Sorting an array in C?

In C, you can use the built in qsort command: see: 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

How do operator.itemgetter() and sort() work?

Looks like you’re a little bit confused about all that stuff. operator is a built-in module providing a set of convenient operators. In two words operator.itemgetter(n) constructs a callable that assumes an iterable object (e.g. list, tuple, set) as input, and fetches the n-th element out of it. So, you can’t use key=a[x][1] there, because python has no idea what x is. … Read more

Sorting list based on values from another list

Shortest Code Example: Generally Speaking Explained: zip the two lists. create a new, sorted list based on the zip using sorted(). using a list comprehension extract the first elements of each pair from the sorted, zipped list. For more information on how to set\use the key parameter as well as the sorted function in general, take a look at this.