I have a question about sorting with C#. I want to implement a function to sort an array of strings such as [“AA”, “A”, “Z”, “ZZZ”] alphabetically without any built-in sort methods. I have tried some Compare function and my logic which is comparison between each character of the two strings, but it does not work properly.
if you compare two strings with the SAME LENGTH like “A” and “Z”, this works fine. The problem is that “Z” comes before “AAA” because it is a shorter string.
That would be appreciated if you could help me out. Thank you.
for (int i = 0; i < copy_database.Length - 1; i++)
{
for (int j = 0; j < copy_database.Length - 1 - i; j++)
{
if (copy_database[j].Value != null && copy_database[j + 1].Value != null)
{
int k = 0;
while (k < Math.Min(copy_database[j].Value.Title.Length, copy_database[j + 1].Value.Title.Length) &&
copy_database[j].Value.Title[k] == copy_database[j + 1].Value.Title[k])
{
k++;
}
if (k < Math.Min(copy_database[j].Value.Title.Length, copy_database[j + 1].Value.Title.Length))
{
if (copy_database[j].Value.Title[k] < copy_database[j + 1].Value.Title[k])
{
// Swap elements
Key_Value_Pair temp = copy_database[j];
copy_database[j] = copy_database[j + 1];
copy_database[j + 1] = temp;
break;
}
}
else
{
break;
}