Help with Sort() understanding

Good afternoon!

I saw a interview question yesterday on r/webdev that puzzled me, I saw the solution and can’t quite get my head around how it works.

The question is, you have a string s = “good” and string t = “odg” and you must sort s in order they appear in t. So in this case the answer would be “oodg”. Great, in my head I can see how that works!

However I’m having trouble with how the Array.Sort method does this. Here’s the solution that was posted.

private string sort(string s, string t)

{

List<char> chars = s.ToCharArray().ToList();

chars.Sort((a, b) => t.IndexOf(a) - t.IndexOf(b));

return String.Join("", chars.ToArray());

}

What I can’t understand is what (a,b) is referring too.

I understand this is a interview question designed to test how you think and work out problems, But I’d still like to know how it works! If there is any resources out there that would help me understand better please let me know!

Thanks!

submitted by /u/arotek
[link] [comments]

Leave a Reply