开发者

Sorting algorithms with respect to type of data being sorted

开发者 https://www.devze.com 2023-02-14 02:37 出处:网络
I have an .NET interview coming up tomorrow and I realized that I\'m kind of weak on my algorithmic side (otherwise I\'m exceptionally good programmer maybe better then you ...haha, joke, who laughed

I have an .NET interview coming up tomorrow and I realized that I'm kind of weak on my algorithmic side (otherwise I'm exceptionally good programmer maybe better then you ... haha, joke, who laughed ?) as I've never programmed any mathematically intense algorithms at my job.

I was wondering what algoritms are best suited/most performant for sorting data of certain types? For example, what algorithm would you use to sort two lists of DateTime in ascending order? No LINQ allowed here, so that you sort them开发者_如何学C fastest?

And similarly, what algoritms are best suited for sorting other types of data, like strings or numbers, etc.?


There are different sorting algorithms, but you can use any of them regardless of the data type, you just need a method to compare two values and determine if they are the same or if one of them is larger than the other.

There are ready made sorting algorithms in the framework, for example the List.Sort method. If you are sorting a list of simple values (like strings, numbers, dates, et.c.) that is already supported as there are default comparers for those:

myList.Sort();

If you are sorting custom objects, you can provide a comparer to the method:

myList.Sort((x, y) => x.Name.CompareTo(y.Name));

If you want to implement a sorting algoritm yourself, you can look at different ones like insert sort, merge sort, quick sort, shell sort, et.c. One of the simplest ones to understand and implement is bubble sort.


Most sorting algorithms are designed around the idea that comparing data elements is a primitive operation (that is, it's not part of the algorithm design). There are exceptions, though (like radix sort).

More interesting is the question of what algorithm is best suited for specific assumptions about the input: is it mostly sorted already; does it all fit in memory without severe performance problems; do tied elements need to stay in their input order; does external data need to be correlated with the sort; etc.

If I were preparing for an interview, I'd bone up on the latter issues. (But I wouldn't want to do it the night before :). Good luck on your interview.)

0

精彩评论

暂无评论...
验证码 换一张
取 消