c# - 在跟踪索引 C# 的同时快速排序数据数组

标签 c# arrays visual-studio sorting quicksort

我在对整数数组使用快速排序算法时遇到了一些问题,同时在排序过程中保存元素移动时的原始索引。使用 C#/Visual Studio 例如

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

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

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

最佳答案

正如@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();

关于c# - 在跟踪索引 C# 的同时快速排序数据数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45351089/

相关文章:

c# - 如何设置几个visual C#项目的输出路径

c++ - 如何在 Microsoft C++ 中打印其他语言字符?

c# - 需要帮助破译 C# 堆栈跟踪

javascript - 在时间数组中查找最近的空闲槽

arrays - JOLT数组转换: add key in all objects in list

php - 将相同的元素压入数组 x 次

c++ - 自动重新排序 MFC 控件 ID

c# - Azure 表存储 - 为什么我的 bool 和 string 属性被存储,但我的 int 和 double 属性却没有存储?

c# - 当用户输入诸如 233,232 之类的数字时,当用户点击逗号左侧的 3 时,如何删除计算器中的逗号

c# - 组合 `using` 语句与一个一个地执行它们一样吗?