Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting of strings by position of another string

What is the best way to do - Given a string A, and collection of strings C, order the strings in the collection in the non decreasing order of the position of A in the strings.

For instance,

A= abc
C= [deabc, abc, dabc, dad] 
Sorted C= [abc, dabc, deabc]

My idea is to iterate over the collection and put it in a HashMap/Dictionary with the position of A in C[i] as index. And then constructing the sorted collection from HashMap. This is not a homework problem. Just wanted to know the efficient way/algorithm of doing this. Any pointers will be helpful.

like image 641
ABC Avatar asked Dec 15 '25 06:12

ABC


1 Answers

Here's a simple way with LINQ:

var SortedC = C.OrderBy (d => d.IndexOf(A)).ToArray();

Note that strings not containing A will be sorted at the beginning because IndexOf returns -1. Also, the behavior for strings with A at the same index is undefined, and will be returned in arbitrary order unless you provide a .ThenBy sort to handle those.

like image 177
mellamokb Avatar answered Dec 16 '25 22:12

mellamokb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!