【问题标题】:Trying to get the number of times a sub query executes尝试获取子查询执行的次数
【发布时间】:2018-12-05 23:45:46
【问题描述】:

我有一些代码可以将数组按升序排序

int[] array = new int[] { 4, 3, 5, 1 };
var result = array.GroupBy(x => x)
                    .OrderBy(g => g.Count())
                    .ThenBy(g => g.Key)
                    .SelectMany(g => g);

我希望能够计算完成排序所需的步骤数。 我要解决的具体问题是: 给定一个由连续整数 [1, 2, 3, ..., n] 组成的无序数组,没有任何重复。您可以交换任意两个元素。您需要找到按升序对数组进行排序所需的最小交换次数。

我可以找到 LINQ 使用的交换次数吗?

这个有可能吗?

例如,如果查询必须将 4 与 1 交换以获得 1、3、5、4,然后将 5 与 4 交换以获得 1、3、4、5,那么这将是 2 个步骤。

【问题讨论】:

  • "计算完成排序所需的步骤数" - 您能否根据您的数组输入给出一个示例输出
  • 但是如果数组由连续的整数组成,那么它已经是升序了。
  • 好吧,你可以实现快速排序,然后在交换完成时计数。 w3resource.com/csharp-exercises/searching-and-sorting-algorithm/…
  • 你需要实现一个排序算法并计算你的算法对数组进行排序需要多少操作(或“交换”)。
  • @Gribbler 我删除了我之前的测试代码。查看新答案;我不能用 linq 来做,而是用我们自己的排序算法。

标签: c# linq


【解决方案1】:

这就是我的想法。我找不到将它与 LINQ 一起使用的方法,但是使用我们自己的排序算法。我做了这样的事情:

static void Main(string[] args)
    {
        ObservableCollection<int> array = new ObservableCollection<int>() {4,3,1,5 };
        int steps = 0;
        array.CollectionChanged+= (sender, e) => 
        {
            Console.WriteLine($"{e.Action} : {string.Join(",", array) }" );
            steps++;
        };

        bool didSwap;
        do
        {
            didSwap = false;
            for (int i = 0; i < array.Count - 1; i++)
            {
                if (array[i] > array[i + 1])
                {
                    int temp = array[i + 1];
                    array[i + 1] = array[i];
                    array[i] = temp;
                    didSwap = true;
                }
            }
        } while (didSwap);


        Console.WriteLine("Sorted Result :");
        foreach(var item in array)
        {
            Console.WriteLine(item);
        }

        Console.WriteLine($"Total Swapps {steps / 2}");

        Console.ReadLine();
    }

这是输出:

【讨论】:

    猜你喜欢
    • 2020-11-18
    • 1970-01-01
    • 2020-03-15
    • 2021-12-19
    • 2020-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多