Fraiser
Fraiser

Reputation: 310

Lexicographical sort algorithm using C#

I am struggling to write a sorting algorithm that can sort characters in a word lexicographically (alphabetically) as follows

lexicographical sort of the word :- Contamination

lexicographically
Sorted Text               Index
------------------         ----------
amination                      0
ation                              1
contamination                2
ination                            3
ion                                  4
mination                          5
n                                    6
nation                            7
ntamination                    8
on                                  9
ontamination                  10
tamination                       11
tion                                12

Could anyone please help write a pseudo code / or an implementation in C# or VB.NET of how I can do a lexicographical sort of the word above?

Upvotes: 3

Views: 6162

Answers (4)

Dilshod Zopirov
Dilshod Zopirov

Reputation: 697

Just try this:

Array.Sort(yourCollection);

Upvotes: 1

Omriko
Omriko

Reputation: 373

The default C# sort function sorts strings lexicographically, so in your case:

YourList.Sort();

should do the trick, if you want to customize the sorting function, you can pass a function to the Sort method:

YourList.Sort((a, b) => SomeSortingFunction(a,b));

When you write SomeSortingFunction make sure it returns a negative value if a is before b, a positive value if a is after b and zero if they are equal.

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292555

string str = "contamination";
IEnumerable<string> sortedSubstrings =
    Enumerable.Range(0, str.Length)
              .Select(i => str.Substring(i))
              .OrderBy(s => s);

Upvotes: 3

Matthew Abbott
Matthew Abbott

Reputation: 61599

You could simply do:

var parts = new List<string>();
for (int i = 0; i < word.Length; i++)
    parts.Add(word.Substring(i));

parts.Sort();

The output should be as you expect.

Upvotes: 6

Related Questions