【问题标题】:Quick sorting a data array while tracking index C#在跟踪索引 C# 时快速排序数据数组
【发布时间】:2017-07-27 12:39:58
【问题描述】:

在整数数组上使用快速排序算法时我有点卡住,同时在排序过程中移动元素时保存元素的原始索引。使用 C#/Visual Studio 例如

ToSort 数组 {52,05,08,66,02,10} 索引:0 1 2 3 4 5

后排序数组 {02,05,08,10,52,66} 索引:4 1 2 5 0 3

我需要将排序值的索引保存在另一个数组中。 我觉得这非常复杂,因为快速排序是递归的,任何帮助或指针将不胜感激!谢谢!

【问题讨论】:

  • 将整数包装在一个包含索引和数字的对象中。然后快速排序。之后,您可以迭代列表以检索值和原始索引。贵族。

标签: c# arrays visual-studio sorting quicksort


【解决方案1】:

正如@Will 所说,您可以这样做:

var myArray = new int[] { 52, 05, 08, 66, 02, 10 };

///In tupple item1 you have the number, in the item2 you have the index  
var myIndexedArray = myArray.Select( ( n, index ) => Tuple.Create( n, index ) );

///Or if you are using c# 7, you can use the tuple literals ! :
var myIndexedArray = myArray.Select( ( n, index ) => ( n, index ) );

///Call your quick sort method, sort by the item1 (the number) inside the method
// or use Enumerable.OrderBy:
myIndexedArray = myIndexedArray.OrderBy(x => x.Item1);

///Then get your things back
int[] numbers = myIndexedArray.Select(x => x.Item1).ToArray();
int[] indexes = myIndexedArray.Select(x => x.Item2).ToArray();

【讨论】:

  • 谢谢卢卡斯,我试试看!
【解决方案2】:

LINQOrderByuses QuickSort internally。因此,与其自己实现 QuickSort,不如使用OrderBy,如果需要,可以使用自定义IComparer<T>

把要排序的数据放入一个匿名类型,记住原来的index,然后按value排序。您可以从已排序元素的index 属性中检索原始索引。

using System.Linq;

var data = new int[] { 52,05,08,66,02,10 };

var sortingDictionary = data
    .Select((value, index) => new { value, index });

var sorted = sortingDictionary
    .OrderBy(kvp => kvp.value)
    .ToList(); // enumerate before looping over result!

for (var newIndex = 0; newIndex < sorted.Count(); newIndex ++) {
    var item = sorted.ElementAt(newIndex);
    Console.WriteLine(
        $"New index: {newIndex}, old index: {item.index}, value: {item.value}"
    );
}

Fiddle

编辑:合并了 mjwills 建议的改进

【讨论】:

  • 谢谢,我在答案中添加了您的改进。
猜你喜欢
  • 2014-08-26
  • 2010-12-07
  • 2016-08-11
  • 2011-12-28
  • 2012-05-21
相关资源
最近更新 更多