The following code is working perfectly for int array but i want to sort array string without using any built in library such as array.sort or .compareTo. so what should i change.
int[] a = { 3, 2, 5, 4, 1 };
int t;
for (int p = 0; p <= a.Length - 2; p++)
{
for (int i = 0; i <= a.Length - 2; i++)
{
if (a[i] > a[i + 1])
{
t = a[i + 1];
a[i + 1] = a[i];
a[i] = t;
}
}
}
foreach (int aa in a)
Console.Write(aa + " ");
Loading

VulpesRank #55 · 29.2K reputationPosted Sep 10, 2014, 3:12 PM EDT
string[] a = { "3", "2", "5", "4", "1" };
string t;
for (int p = 0; p <= a.Length - 2; p++)
{
for (int i = 0; i <= a.Length - 2; i++)
{
if (a[i][0] > a[i + 1][0])
{
t = a[i + 1];
a[i + 1] = a[i];
a[i] = t;
}
}
}
foreach (string aa in a)
Console.Write(aa + " ");
However, if the strings are of any length, then you'd need to write your own equivalent of the CompareTo method as strings in C# don't support the '>' operator even for strictly lexical comparisons.
VulpesRank #55 · 29.2K reputationPosted Sep 11, 2014, 12:11 PM EDT
Now the > operator works for the char type and c1 > c2 is true if c1's unicode value is greater than c2's unicode value.
The unicode (or ascii) value of the digit '0' is 48, '1' is 49 and so on up to '9' which is 57.
So you can see now that the effect of this code is to sort digits in order just like their corresponding numeric values (0 to 9) were sorted when you used an int array.
Also, since the ascii values of A-Z are 65 to 90 and of a-z are 97 to 122, the code would correctly sort single character alphabetic strings as well.
Jignesh TrivediRank #16 · 50.3K reputationPosted Sep 10, 2014, 7:59 PM EDT
Please refer below form link
http://www.c-sharpcorner.com/Forums/Thread/159202/bubble-sort-using-string-array-in-C-Sharp.aspx
hope this will help you.
Muhammad Adeel56 reputationPosted Sep 11, 2014, 9:13 AM EDT
Muhammad Adeel56 reputationPosted Sep 12, 2014, 8:31 AM EDT
Muhammad Adeel56 reputationPosted Sep 12, 2014, 8:31 AM EDT
Muhammad Adeel56 reputationPosted Sep 12, 2014, 8:31 AM EDT
Muhammad Adeel56 reputationPosted Sep 12, 2014, 8:31 AM EDT
Muhammad Adeel56 reputationPosted Sep 12, 2014, 8:31 AM EDT
Muhammad Adeel56 reputationPosted Sep 12, 2014, 8:31 AM EDT
Muhammad Adeel56 reputationPosted Sep 12, 2014, 8:31 AM EDT
Muhammad Adeel56 reputationPosted Sep 12, 2014, 8:31 AM EDT