Sorting two arrays (values,keys), then sorting the keys

I have what seems to be a simple problem but I can't figure it out so far.

Say I have two arrays:

int[] values = {10,20,20,10,30}; int[] keys = {1,2,3,4,5}; Array.Sort(values,keys);

Then the arrays would look like this:

values = {10,10,20,20,30}; keys = {4,1,2,3,5};

Now, what I want to do is make it so that the keys are also sorted in second priority so the key array to look like this:

keys = {1,4,2,3,5};

Notice the 1 and 4 values are switched and the order of the value array has not changed.

-------------Problems Reply------------

If an "in-place sorting" is not strictly necessary for you, I suggest to use OrderBy:

var sortedPairs = values.Select((x, i) => new { Value = x, Key = keys[i] })
.OrderBy(x => x.Value)
.ThenBy(x => x.Key)
.ToArray(); // this avoids sorting 2 times...
int[] sortedValues = sortedPairs.Select(x => x.Value).ToArray();
int[] sortedKeys = sortedPairs.Select(x => x.Key).ToArray();

// Result:
// sortedValues = {10,10,20,20,30};
// sortedKeys = {1,4,2,3,5};

Generally, parallel arrays are frowned upon. It is very easy for the data to become out of sync. What I would suggest is either using a map/Dictionary data type, or storing the keys and values in a single object, and then having an array of said objects.

Edit: after re-reading your question, I dont' think the Dictionary is the data type you want, based on your need to sort the values. I would still suggest having an object that contains the keys and values, however. You can then sort by the values, and rest assured that they keys aren't out of sync.

Array.Sort(values,keys) will use the default Comparer to sort the values and keys. You would need to write a custom Comparer to do what you're describing, and pass your Comparer in to the Array.Sort method.

By converting this to a sort on an array of value pairs you can supply your own comparator and make the sort work pretty much any way you like. (It seems awful risky to use two separate arrays.) See the fourth method at

Category:c# Views:0 Time:2010-11-29
Tags: c# arrays

Related post

  • Sorting an array on value and not on key 2013-10-02

    I want to sort this array: Array ( [0] => Array ( [qid] => 1_2_qb0 [hendel] => 7.7 ) [1] => Array ( [qid] => 1_2_qb1 [hendel] => 4.13 ) [2] => Array ( [qid] => 1_2_qb2 [hendel] => 6.61 ) [3] => Array ( [qid] => 1_2_qb

  • Sorting an array by its members' dictionary's keys 2011-03-29

    If that was a little confusing here's a visual representation: Array > Object > Dictionary > Values Here's some context if this helps: An array contain playlists. Each playlist has a dictionary. Each dictionary contains metadata. I need to s

  • Sort an array which is partially sorted 2010-10-21

    I am trying to sort an array which has properties like it increases upto some extent then it starts decreasing, then increases and then decreases and so on. Is there any algorithm which can sort this in less then nlog(n) complexity by making use of i

  • Sort an array with respect to sorting of an another array iphone sdk 2011-09-23

    I have a situation here, I have two arrays,array1 and array2 and one tableview. I have loaded array1 to the table view. So here, I'm sorting array2, I've done that, but how can I sort array1 with respect to the change in array2 and to reload array1 i

  • Ouput is not expected in sorting coin array values using selection sorting 2014-01-30

    I want to sort a Coin array according to their values by using Selection sort but the output is not showing properly. The output display as some other unique format. I have tried to resolve the problem but still unable to find the solution. I have tw

  • Sorting an array of dictionaries based on dictionary keys 2010-02-13

    I was wondering if someone can show me how to sort an NSDictionary; I want to read it starting from the last entry, since the key is Date + Time and I want to be able to append it to an NSMutableString. I was able to read it using an enumerator but I

  • Sorting multidimensional array, upper case being sorted before lowercase 2012-05-01

    Using the below for sorting a multidimensional array by screen name: $sortArray = array(); foreach($members as $member){ foreach($member as $key=>$value){ if(!isset($sortArray[$key])){ $sortArray[$key] = array(); } $sortArray[$key][] = $value; } }

  • multiple key to sort array 2010-09-24

    I have NSMutableArray in which all object is in NSMutableDictionary i want to sort this array base on NSMutableDictionary with two key one is country and another is name. Can any one Help me to use NSSort class to sort the array using multiple key. T

  • Sorting an array according to a key in multi dimensional array and preserving other key values. PHP 2011-10-14

    This is my array. Array ( [Data] => Array ( [0] => Array ( [recipeid] => 108 [recipe] => Rasams- the tongue ticklers ! [image] => No data [category] => Rasams and Soups ) [1] => Array ( [recipeid] => 44 [recipe] => Brain Bo

  • Sorting an array of arrays by the child array's length? 2009-01-22

    What's the best way in PHP to sort an array of arrays based on array length? e.g. $parent[0] = array(0, 0, 0); $parent[2] = array("foo", "bar", "b", "a", "z"); $parent[1] = array(4, 2); $sorted = sort_by_length($parent) $sorted[0] = array(4, 2); $sor

  • Sorting an array of objects by property? 2009-07-15

    Say I have an array of JavaScript objects: var objs = [ { first_nom: 'Lazslo', last_nom: 'Jamf' }, { first_nom: 'Pig', last_nom: 'Bodine' }, { first_nom: 'Pirate', last_nom: 'Prentice' } ]; How can I sort them by the value of last_nom in JavaScript?

  • How to sort an array in this way in php 2009-10-22

    like the function usort in php but if two members compare as equal, their key should be same. for example: $arrayToSort = array(2,6,1,3,3); after sort return array 1 => 1 2 => 2 3 => 3 3 => 3 4 => 6 --------------Solutions-------------

  • How to sort an array in php 2009-11-12

    i want the same value has the same index for example 1 2 2 3 5 after sort: array( 0=>1 1=>2 1=>2 3=>3 4=>5); but we can not set duplicate index in the array of php. --------------Solutions------------- There's a sort function in php! (

  • How to sort an array of structs in ColdFusion 2010-04-16

    I have an array of structs in ColdFusion. I'd like to sort this array based on one of the attributes in the structs. How can I achieve this? I've found the StructSort function, but it takes a structure and I have an array. If this is not possible pur

  • Sorting nested arrays in JavaScript 2011-10-12

    I'm totally stuck and blank on how to solve this sort problem. JS object o={"items":[ {"name":"Name 1","types":[ {"type":"Type 4","subtype":"Sub a"} ]}, {"name":"Name 2","types":[]}, {"name":"Name 3","types":[ {"type":"Type 1","subtype":"Sub x"} ]} ]

  • Simple function to sort an array of objects 2011-11-17

    I would like to create a (non-anonymous) function that sorts an array of objects alphabetically by the key name. I only code straight-out JavaScript so frameworks don't help me in the least. var people = [ {'name': 'a75', 'item1': false, 'item2': fal

  • Sorting an array with jQuery JSON data 2011-12-07

    I was trying to figure out how to sort an array provided by a php script. The php script gets the html files in a directory, and then passes them to jQuery, which then fetches them and displays them on the page. This is what I have: <script> $(

  • PHP sorting multidimensional array, can only sort one column 2012-02-20

    Firstly, YES, this is a duplicate issue that's been asked 100 times on here, and I've read through many of the posts, but the examples given aren't working 100% for me and I can't figure out where I'm going wrong. I want to sort an array like this by

  • Sort multidimensional array in JavaScript 2010-08-10

    I need to sort an array containing arrays in ascending numerical order. The data structure looks like this array = [[escalation],//integer [name], [email], [blackberry]]; I try to sort the array using this function (sorting by escalation) function so

  • Sorting an Array List of String[] arrays 2011-09-06

    I am reading in a .csv file sort of like a spreadsheet in excel. There are a certain number of columns, determined by the file, and I read each line into a string array using the .split(",") method. I then put this into an array list so it can hold a

Copyright (C), All Rights Reserved.

processed in 0.147 (s). 11 q(s)