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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
VulpesPosted Oct 2, 2013, 6:18 AM
And here's another approach which uses the Gnome sort algorithm (http://en.wikipedia.org/wiki/Gnome_sort):
VulpesPosted Oct 2, 2013, 7:52 AM
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.
Prasanth RPosted Oct 2, 2013, 7:06 AM
Jeetendra GundPosted Oct 2, 2013, 2:54 AM
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.
TulasiPosted Oct 2, 2013, 1:11 AM
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);
}