3

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.

7
  • 1
    Can you make use of LINQ? Commented Jan 18, 2013 at 16:45
  • 1
    var results = yourList.OrderBy(str=>str.IndexOf("abc")) Commented Jan 18, 2013 at 16:46
  • 2
    What's the output when C = [abc, dabc, dabd]? Commented Jan 18, 2013 at 16:48
  • what about performance? if LINQ cannot be used, is there a efficient way to do this? Commented Jan 18, 2013 at 16:49
  • 1
    @AustinSalonen, sorry. output is C = [abc, dabc] Commented Jan 18, 2013 at 16:52

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

maybe you mean d.IndexOf(a) ?
If the strings are long maybe could be convenient to do: var sorted = C.Select(x => new {Str=x,Pos=x.IndexOf(A)}).OrderBy(x => x.Pos).Select(x => x.Str);
@mellamokb, is there a way to filter -1 values (a not found in d) in the order by clause?
Do you want to leave them out entirely? If so, do C.Where(d => d.IndexOf(A) != -1).OrderBy...
1
stringsArray.OrderBy(s => s.IndexOf("a"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.