A
A
Andrey Fomin2020-05-09 14:05:00
C++ / C#
Andrey Fomin, 2020-05-09 14:05:00

How to count the number of permutations and comparisons?

Hello
There is an implementation of the quicksort algorithm in C#

using System;

class Program
{
    //метод для обмена элементов массива
    static void Swap(ref int x, ref int y)
    {
        var t = x;
        x = y;
        y = t;
    }

    //метод возвращающий индекс опорного элемента
    static int Partition(int[] array, int minIndex, int maxIndex)
    {
        var pivot = minIndex - 1;
        for (var i = minIndex; i < maxIndex; i++)
        {
            if (array[i] < array[maxIndex])
            {
                pivot++;
                Swap(ref array[pivot], ref array[i]);
            }
        }

        pivot++;
        Swap(ref array[pivot], ref array[maxIndex]);
        return pivot;
    }

    //быстрая сортировка
    static int[] QuickSort(int[] array, int minIndex, int maxIndex)
    {
        if (minIndex >= maxIndex)
        {
            return array;
        }

        var pivotIndex = Partition(array, minIndex, maxIndex);
        QuickSort(array, minIndex, pivotIndex - 1);
        QuickSort(array, pivotIndex + 1, maxIndex);

        return array;
    }

    static int[] QuickSort(int[] array)
    {
        return QuickSort(array, 0, array.Length - 1);
    }

    static void Main(string[] args)
    {
        Console.Write("N = ");
        var len = Convert.ToInt32(Console.ReadLine());
        var a = new int[len];
        for (var i = 0; i < a.Length; ++i)
        {
            Console.Write("a[{0}] = ", i);
            a[i] = Convert.ToInt32(Console.ReadLine());
        }

        Console.WriteLine("Упорядоченный массив: {0}", string.Join(", ", QuickSort(a)));

        Console.ReadLine();
    }
}

And you need to count the number of permutations and comparisons when executing the code.
How can this be implemented?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
#
#, 2020-05-09
@a63826ndrew

you need to count the number of permutations and comparisons when executing the code

- create global variables for counters (or pass in parameters as outand / or ref)
- where comparison , increment the desired counter
- where permutation , increment another

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question