Search code examples
c#stopwatchinsertion-sort

.NET's Stopwatch Class, behaves strange


so, i have all the search algorithms, and i am sending random 20000 numbers to each algorithm, trying to figure out how long each will take.

        public void functionsForSorts(int[] array)
    {
        Stopwatch sw = new Stopwatch();
        long elapsedTime = sw.ElapsedTicks;

        if (array.Length == 20000) 
        {
            sw.Start();
            BubbleSort.Bubble(array);
            sw.Stop();
            elapsedTime = sw.ElapsedMilliseconds;
            label1.Text += "\t" + elapsedTime.ToString() + " miliseconds ";
            Application.DoEvents();

            sw.Restart();
            SelectionSort.Selection(array);
            sw.Stop();
            elapsedTime = sw.ElapsedMilliseconds;
            label2.Text += "\t" + elapsedTime.ToString() + " miliseconds ";
            Application.DoEvents();

            sw.Restart();
            InsertionSort.Insertion(array);
            sw.Stop();
            elapsedTime = sw.ElapsedMilliseconds;
            label3.Text += "\t" + elapsedTime.ToString() + " miliseconds ";
            Application.DoEvents();

            sw.Restart();
            MergeSort.mergeSort(array, 0, array.Length - 1);
            sw.Stop();
            elapsedTime = sw.ElapsedMilliseconds;
            label4.Text += "\t" + elapsedTime.ToString() + " miliseconds ";
            Application.DoEvents();

            sw.Restart();
            ShellSort.Shell(array);
            sw.Stop();
            elapsedTime = sw.ElapsedMilliseconds;
            label5.Text += "\t" + elapsedTime.ToString() + " miliseconds ";
            Application.DoEvents();

            sw.Restart();
            QuickSort.Quicksort(array, 0, array.Length - 1);
            sw.Stop();
            elapsedTime = sw.ElapsedMilliseconds;
            label6.Text += "\t" + elapsedTime.ToString() + " miliseconds ";
            Application.DoEvents();
        }

the problem is stopwatch won't give proper results, it works ok for bubble sort, selection sort and merge sort, but i don't know why, it always writes 0 for insertionsort, even though it has a proper value while debugging.and it doesnt give proper values for shell sort and quick sort too.

Another awkward part about this, when i comment out bubble and selection sort, Insertion will give proper results, this is true for all the algorithms, if i make them the 1st one in order, im getting proper results, i showed this to my friends, they don't have any clue either, this really doesn't make sense at all...


Solution

  • If the array is already sorted, it's possible your insertion sort had nothing to do and finished in less than 1 millisecond. That could be possible if your previous sort left the array sorted.

    (Edit - I apparently have a really hard time typing the word "possible" instead of "possibly"... corrected.)