if suppose i have
Dhoni
Raina
Jadeja
Albie
as my string i have to sort it as
Albie
Dhoni
Jadeja
Raina
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
VulpesRank #55 · 29.2K reputationPosted Oct 2, 2013, 2:18 AM EDT
And here's another approach which uses the Gnome sort algorithm (http://en.wikipedia.org/wiki/Gnome_sort):
TulasiRank #2,544 · 549 reputationPosted Oct 1, 2013, 9:11 PM EDT
With LINQ :
string[] strarray=new string[]
{
"Dhoni",
"Raina",
"Jadeja",
"Albie"
}
var sort=from s in strarray orderby s select s;
foreach (string c in sort)
{
Console.writeLine(c);
}
Jeetendra GundRank #97 · 22.1K reputationPosted Oct 1, 2013, 10:54 PM EDT
Prasanth,
Try this,
class Program
{
static void Main(string[] args)
{
string[] str = new string[] {"Dhoni", "Raina", "Jadeja", "Albie"};
int cnt = str.Length - 1;
for(int i = 0; i < cnt; i++)
{
for(int j = cnt; j > i; j--)
{
if(((IComparable)str[j-1]).CompareTo(str[j])>0)
{
var temp = str[j-1];
str[j-1] = str[j];
str[j] = temp;
}
}
}
foreach(var item in str)
{
Console.WriteLine(item);
}
}
}
Thanks.
Prasanth R21 reputationPosted Oct 2, 2013, 3:06 AM EDT
VulpesRank #55 · 29.2K reputationPosted Oct 2, 2013, 3:52 AM EDT
These letters have ASCII/Unicode values between 65 and 90 inclusive. So, if you subtract 65, you're going to be left with a number between 0 and 25.
The alpha array has 26 elements, one for each letter, so the expression name[0] - 65 will therefore give you the appropriate index into this array.
For example, if you take "Dhoni" the ASCII value of 'D' is 68 and subtracting 65 leaves 3. We therefore set alpha[3] equal to "Dhoni".
The alpha array will therefore end up containing all the names in the correct order and if you remove those elements that are null and assign the other elements back to the names array they will be in sorted order.