none
C# sort, yield or all evaluated at the same time RRS feed

  • General discussion

  • Hi,

    This is just an exercise and I have given it ago Lets say your given an unordered collection which in theory could get quite large. 

    You want to sort it by property1 and property2. Then sort it by property2 and property1. 

    I have used 2 classes which implement the icomparer interface. 

    Now I'm quite certain by comparers are correct. 

    I used this solution because instead of creating a copy of the collection it that collection which is going to be better in terms of memory.

    However im wondering if there is a more efficient way to search one that maybe yields as soon as one item in the collection is correctly sorted. That way you can display the 1st item, second item etc etc on the UI. 

    does anyone have any suggestions on how to improve this? 

    Thanks.

    Monday, January 21, 2019 7:49 AM

All replies

  • You don't mention which sort you are using.  Are you using the standard List.Sort or Array.Sort operation?  The documentation describes the sort algorithm they use (a blend of QuickSort and HeapSort).

    You use the word "efficient".  Nothing you do is going to make the sorting more efficient.  The efficiency of those algorithms is well-established in the literature.  Your desire to start displaying the top items as soon as possible is a reasonable one, although it's going to make the sorting take longer overall.

    You can't hook into the library algorithm, so to do what you ask, you'd have to implement the sort yourself.  It's not rocket science.  HeapSort does almost exactly what you say; it scans the data to produce an "index", then it uses the index to find the sorted values in order, one by one.  You could write your own HeapSort and just display the items as they fall out.

    HeapSort is not as fast as QuickSort, but QuickSort works recursively.  It divides the data set into smaller and smaller chunks until it's trivial to put each chunk in order.  Thus, you don't necessarily get the items in order.  Since you are adding the overhead of UI, the difference in performance of the two algorithms is probably not important.


    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    Tuesday, January 22, 2019 12:24 AM