Please guide me as how to sort an array with taking into consideration that each row is specific to one specific column value. For example,
1D array
5 3 42D array
1,2,3 3,4,5 6,7,8In above example,let say, 5 (In 1Darray) is associated with the first row of 2d array (1,2,3). Similary, 3 in 1d array is associated with second row of 2d array(3,4,5).And similarly for the third entry of 4 (of 1d array). Now I want to sort the 1D array with taking into consideration that the associated rows with each 1D array element also change accordingly. I mean its kind of auto-arrangment of row开发者_如何学Gos with change of column values. Please guide Regards Asad
Without bothering with complex things you could just map every sortex index of the 1D array to the correct row.
You basically keep both arrays without effectively sorting them and you store inside another int array the sorted indices. For your example you would have a third array
[1,2,0]
in which first position maps to second row of 1D and 2D array, that is also the smaller element.. and so on.
An idea. Have an array with the position of the source array matching boths of them. Let me explain:
You have an array 1D, let's say
var oneDArray = new int[]; //fill it.. :)
var twoDArray = new int[,]; //fill it.. :)
var mapping = new int[oneDArray.Length];
//lets create the mapping
for (int i = 0; i < mapping.Lenght; i++)
mapping[i] = i;
//now lets sort the 1D array
for (int i = 0; i < oneDArray.Length; i++)
for (int j = i; j < oneDArray.Length; i++){
if ( oneDArray[i] < oneDArray[j] ){
Swap(oneDArray, i, j);
Swap(mapping, i, j);
}
}
The swap method receives an array and two values, i and j and swaps the i-eth value with the j-eth value of the array. If you swap the mappings, then, you can see where are the corresponding values of the 3D array. So mapping[i] will have where the vector corresponding to the i-eth number of 1D is on 2D.
I hope i havent made a mess... Best regards!
精彩评论