所以我有這種氣泡排序,第一次嘗試創建一個,這就是我所擁有的。 出於某種原因,它以奇怪的方式打印出數組。據我所知,它應該用字母排序。爲什麼我的氣泡不能正確排序我的數組?
如何正確地做一個冒泡排序而不使用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循環中。現在,除了第二個值之外,它將打印出所有內容。 –