Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting on insertion with a comparing function

I'm trying to sort data of a type T in a container by two of T's properties. It's potentially a lot of data, so I would much rather have the sorting happen on insertion. I've looked into both List and SortedList, but both don't quite provide the functionality I need.

Does C# provide a container that allows both sorting on insertion and sorting my a comparison function? I would like to avoid post insertion sorting like List.Sort, and avoid the overhead of using the data as both key and value for SortedList.

like image 838
jbarba Avatar asked Jul 18 '12 19:07

jbarba


People also ask

Does insertion sort compare?

Insertion Sort is a simple comparison based sorting algorithm. It inserts every array element into its proper position.

How do you count comparisons in insertion sort?

Hence, the total number of comparisons required by insertion sort in the worst case is (N - 1)×1/2N = 1/2(N2 - N). This formula gives 10 comparisons for a 5 item list, as we would expect from Figure 5.15 part (a).

How many comparisons does 5 elements have in insertion sort?

4.

How do you calculate comparisons for selection sort?

In general, the average number of comparisons per pass in selection sort will always be one half of the number of items to be sorted. For eight items, we have 1/2(82 + 8) = 1/2(64 + 8) = 1/2(72) = 36 comparisons.


1 Answers

If you're using .NET 4, you could use SortedSet with a custom IComparer<T>. The downside is that it won't allow you to have multiple equal elements. Do you need that?

It's not clear to me why you want sorting on insertion just because you've got a lot of data though. Do you need it to be sorted before you've finished inserting? If not, I'd expect a single sort at the end (via List.Sort) to be as efficient as an as-you-go sort.

like image 171
Jon Skeet Avatar answered Sep 23 '22 08:09

Jon Skeet