所以我有这种气泡排序,第一次尝试创建一个,这就是我所拥有的。 出于某种原因,它以奇怪的方式打印出数组。据我所知,它应该用字母排序。为什么我的气泡不能正确排序我的数组?
如何正确地做一个冒泡排序而不使用LINQ或Array.Sort();这是为了学校,所以我需要做泡沫排序算法。
这里是它打印出来的图像。
class Program
{
static string[] animals = new string[] { "cat", "elephant", "tiger", "fish", "dolphin", "giraffe", "hippo", "lion", "rat", "string ray" };
static void Main(string[] args)
{
BubbleSort();
Console.ReadLine();
}
private static void BubbleSort()
{
bool swap;
string temp;
string[] animals = new string[] { "cat", "elephant", "tiger", "fish", "dolphin", "giraffe", "hippo", "lion", "rat", "string ray" };
for (int index = 0; index < (animals.Length - 1); index++)
{
if (string.Compare(animals[index], animals[index + 1], true) < 0) //if first number is greater then second then swap
{
//swap
temp = animals[index];
animals[index] = animals[index + 1];
animals[index + 1] = temp;
swap = true;
}
}
foreach (string item in animals)
{
Console.WriteLine(item);
}
}
}
您只将一个元素冒泡到它在数组中的正确位置(假设您_meant_在最后具有最小值,否则反转您的比较运算符) - 冒泡排序需要多次通过数组。 –
我将CompareTo <转换为CompareTo>,并将其全部添加到foreach循环中。现在,除了第二个值之外,它将打印出所有内容。 –