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
VulpesPosted Sep 10, 2014, 7:12 PM
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.
Muhammad AdeelPosted Sep 12, 2014, 12:31 PM
Muhammad AdeelPosted Sep 12, 2014, 12:31 PM
Muhammad AdeelPosted Sep 12, 2014, 12:31 PM
Muhammad AdeelPosted Sep 12, 2014, 12:31 PM
Muhammad AdeelPosted Sep 12, 2014, 12:31 PM
Muhammad AdeelPosted Sep 12, 2014, 12:31 PM
Muhammad AdeelPosted Sep 12, 2014, 12:31 PM
Muhammad AdeelPosted Sep 12, 2014, 12:31 PM
VulpesPosted Sep 11, 2014, 4:11 PM
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.
Muhammad AdeelPosted Sep 11, 2014, 1:13 PM
Jignesh TrivediPosted Sep 10, 2014, 11:59 PM
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.