C# - Fastest Way To Sort Array Of Primitives And Track Their Indices

最后都变了- 提交于 2019-12-05 08:35:42
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

Basically, the 2-argument version of Array.Sort applies the same operations to both arrays, running the actual sort comparisons on the first array. This is normally used the other way around - to rearrange something by the desired indices; but this works too.

You can use the overload of Array.Sort() which takes TWO arrays, and sorts the second one according to how it sorted the first one:

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);

You can create a new array of indices, and then sort both of them using Array.Sort and treating input as keys:

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);

if you use 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();

in results you got objects with values and their indexes.

A List<KeyValuePair<int,float>> and a custom sorter would also work. the key for each pair holds the original index.

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


    }
    private int SortByValue(KeyValuePair<int, float> a, KeyValuePair<int, float> b)
    {
        return a.Value.CompareTo(b.Value);
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!