C# – 排序基元数组并跟踪其指数的最快方法

我需要一个float[]进行排序。 我需要知道旧数组在新数组中的位置。 这就是为什么我不能使用Array.Sort(); 管他呢。 所以我想编写一个为我排序数组的函数,并记住每个值占用的索引:

 float[] input = new float[] {1.5, 2, 0, 0.4, -1, 96, -56, 8, -45}; // sort float[] output; // {-56, -45, -1, 0, 0.4, 1.5, 2, 8, 96}; int[] indices; // {6, 8, 4, 2, 3, 0, 1, 7, 5}; 

arrays的大小约为500.我该如何处理? 什么排序算法等


解决之后:总是让我惊讶的是C#有多强大。 我甚至没有能够自己完成这项任务。 因为我已经听说过Array.Sort()非常快,我会接受它。

 float[] input = new float[] { 1.5F, 2, 0, 0.4F, -1, 96, -56, 8, -45 }; int[] indices = new int[input.Length]; for (int i = 0; i < indices.Length; i++) indices[i] = i; Array.Sort(input, indices); // input and indices are now at the desired exit state 

基本上, Array.Sort的2参数版本对两个数组应用相同的操作,在第一个数组上运行实际的排序比较。 这通常用于反过来 - 通过所需的索引重新排列某些东西; 但这也有效。

您可以使用带有两个数组的Array.Sort()的重载,并根据它对第一个数组的排序方式对第二个数组进行排序:

 float[] input = new [] { 1.5f, 2, 0, 0.4f, -1, 96, -56, 8, -45 }; int[] indices = Enumerable.Range(0, input.Length).ToArray(); Array.Sort(input, indices); 

您可以创建一个新的索引数组,然后使用Array.Sort对它们进行排序并将input视为键:

 float[] input = new float[] { 1.5F, 2, 0, 0.4F, -1, 96, -56, 8, -45 }; int[] indicies = Enumerable.Range(0, input.Length).ToArray(); Array.Sort(input, indicies); 

如果你使用linq:

  float[] input = new float[] { 1.5F, 2, 0, 0.4F, -1, 96, -56, 8, -45 }; var result = input.Select(x => new { Value = x, Index = input.ToList().IndexOf(x)}).OrderBy(x => x.Value).ToList(); // sort float[] output = result.Select(x => x.Value).ToArray(); int[] indices = result.Select(x => x.Index).ToArray(); 

在结果中,您获得了具有值及其索引的对象。

List>和自定义排序器也可以工作。 每对的密钥保存原始索引。

  private void Form1_Load(object sender, EventArgs e) { List> data = new List> { new KeyValuePair(0,1.5f), new KeyValuePair(1,2), new KeyValuePair(2,0), new KeyValuePair(3,0.4f), new KeyValuePair(4,-1), new KeyValuePair(5,96), new KeyValuePair(6,-56), new KeyValuePair(7,8), new KeyValuePair(8,-45) }; data.Sort(SortByValue); foreach (KeyValuePair kv in data) { listBox1.Items.Add(kv.Key.ToString() + " - " + kv.Value.ToString()); } } private int SortByValue(KeyValuePair a, KeyValuePair b) { return a.Value.CompareTo(b.Value); }