I have created a class as follows:
public class StringMatch
{
public int line_num;
public int num_of_words;
}
I have created a list
List<StringMatch> sm;
it has few elements in it.
How do I sort this list using the Comparison<T>
comparison overload?
The sorting must be done based on the num_of_words
field.
For simplicity, we will be using Selection Sort in this article. The array can be sorted in ascending order by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array.
C language provides five sorting techniques, which are as follows − Bubble sort (or) Exchange Sort. Selection sort. Insertion sort (or) Linear sort. Quick sort (or) Partition exchange sort.
Below is a simple insertion sort algorithm for a linked list. 1) Create an empty sorted (or result) list 2) Traverse the given list, do following for every node. ......a) Insert current node in sorted way in sorted or result list. 3) Change head of given linked list to head of sorted (or result) list.
Merge sort is often preferred for sorting a linked list. The slow random-access performance of a linked list makes some other algorithms (such as quicksort) perform poorly, and others (such as heapsort) completely impossible.
You can write lambda expression comparing two objects like this:
sm.Sort((x,y)=>x.num_of_words.CompareTo(y.num_of_words));
you can inverse sorting adding -
sm.Sort((x,y)=>-x.num_of_words.CompareTo(y.num_of_words));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With