Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an array related to another array

Tags:

arrays

c#

I have two arrays, x and y, where y is the value of the tens of every element in x. Now, I want to sort y. But, the order of y will be different of x's. So, I can't tell after sorting which element in y was related to, for instance, x[0].

I want a "double sorting" maybe.

like image 664
Loai Abdelhalim Avatar asked Dec 26 '09 20:12

Loai Abdelhalim


People also ask

How do you sort an array based on another array?

Method 1 (Using Sorting and Binary Search)Create a temporary array temp of size m and copy the contents of A1[] to it. Create another array visited[] and initialize all entries in it as false. visited[] is used to mark those elements in temp[] which are copied to A1[]. Initialize the output index ind as 0.

How do you sort an array of objects in JavaScript based on another array?

const arr1 = ['d','a','b','c'] ; const arr2 = [{a:1},{c:3},{d:4},{b:2}]; We are required to write a JavaScript function that accepts these two arrays. The function should sort the second array according to the elements of the first array.

What is relative sorting?

Relative Sort Array. Easy. Given two arrays arr1 and arr2 , the elements of arr2 are distinct, and all elements in arr2 are also in arr1 . Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2 .


1 Answers

Array.Sort has an overload that accepts two arrays; one for the keys, and one for the items. The items of both are sorted according to the keys array:

int[] keys = { 1, 4, 3, 2, 5 }; string[] items = { "abc", "def", "ghi", "jkl", "mno" }; Array.Sort(keys, items); foreach (int key in keys) {     Console.WriteLine(key); // 1, 2, 3, 4, 5 } foreach (string item in items) {     Console.WriteLine(item); // abc, jkl, ghi, def, mno } 

So in your case, it sounds like you want:

Array.Sort(y,x); // or Sort(x,y); - it isn't  100% clear 
like image 168
Marc Gravell Avatar answered Sep 19 '22 19:09

Marc Gravell