Reputation: 367
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";
}
If I run this twice, using the same unsorted randomly generated array here:
randomArray = randomizedArray
(Convert.ToInt32(textBox1.Text), Convert.ToInt32(textBox2.Text));
randomArrayGnome = randomArray;
randomArrayBubble = randomArray;
randomArrayInsertion = randomArray;
GnomeSort(randomArray);
BubbleSort(randomArrayBubble);
But it outputs something close to this:
Gnome Sorting completed, total time taken 00:00:02.5419864
Bubble Sorting completed, total time taken 00:00:00.0003556
but if I switch the call order, the times are drastically different, instead Bubble Sorting may take 6 seconds. What is happening here? How come it isn't sorting them correctly?
Upvotes: 0
Views: 84
Reputation: 20575
randomArray
& randomArrayGnome
both holds the reference to randomizedArray
.
When you call
GnomeSort(randomArray);
BubbleSort(randomArrayBubble);
the reference array is already sorted, BubbleSort
is working on a already sorted array!
You can use Array.Clone()
so that four different reference are created!
Upvotes: 2
Reputation: 70122
Your problem is with your initialisation of the arrays. As shown here:
randomArray = randomizedArray
(Convert.ToInt32(textBox1.Text), Convert.ToInt32(textBox2.Text));
randomArrayGnome = randomArray;
randomArrayBubble = randomArray;
randomArrayInsertion = randomArray;
The above code creates four variables that all reference the same array. So what happens is that the first sort algorithm sorts the array, subsequent ones will encounter an array that is already sorted so will execute very fast.
As simple solution is to use a Linq - ToList to clone the array:
randomArray = randomizedArray
(Convert.ToInt32(textBox1.Text), Convert.ToInt32(textBox2.Text));
randomArrayGnome = randomArray.ToList();
Upvotes: 3