我在对整数数组使用快速排序算法时遇到了一些问题,同时在排序过程中保存元素移动时的原始索引。使用 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/