public void GnomeSort<T>(IList<T> list, IComparer<T> comparer)
{
sortTimer = new Stopwatch();
sortTimer.Start();
bool stillGoing = true;
while (stillGoing)
{
stillGoing = false;
for (int i = 1; i < list.Count; )
{
T x = list[i - 1];
T y = list[i];
if (comparer.Compare(x, y) <= 0)
i++;
else
{
list[i - 1] = y;
list[i] = x;
i--;
if (i == 0)
i = 1;
stillGoing = true;
}
}
}
sortTimer.Stop();
richTextBox1.Text += "Gnome Sorting completed, total time taken " + sortTimer.Elapsed + "\n";
}
如果我运行两次,在这里使用相同的未排序随机生成的数组:
randomArray = randomizedArray
(Convert.ToInt32(textBox1.Text), Convert.ToInt32(textBox2.Text));
randomArrayGnome = randomArray;
randomArrayBubble = randomArray;
randomArrayInsertion = randomArray;
GnomeSort(randomArray);
BubbleSort(randomArrayBubble);
但它输出的东西接近这个:
Gnome Sorting completed, total time taken 00:00:02.5419864
Bubble Sorting completed, total time taken 00:00:00.0003556
但是如果我切换调用顺序,时间会大不相同,而不是冒泡排序可能需要 6 秒。这里发生了什么?为什么它没有正确排序它们?