c# - sort two dimension array -
i need sort 2 dimension array in ascending order ,i write code in c# sort array sort each line in array not 2 dimension array , how can sort 2 dimension array
double[,] test_descriptor = new double[3, 3]; double tempr; test_descriptor[0,0]=7; test_descriptor[1, 0] = 7; test_descriptor[2, 0] = 5; test_descriptor[0, 1] = 3; test_descriptor[1, 1] = 0; test_descriptor[2, 1] = 2; test_descriptor[0, 2] = 1; test_descriptor[1, 2] = 9; test_descriptor[2, 2] = 1; (int = 0; < test_descriptor.getlength(0); i++) // array sorting { (int j = test_descriptor.getlength(1) - 1; j > 0; j--) { (int k = 0; k < j; k++) { if (test_descriptor[i, k] > test_descriptor[i, k + 1]) { tempr = test_descriptor[i, k]; test_descriptor[i, k] = test_descriptor[i, k + 1]; test_descriptor[i, k + 1] = tempr; } } } } (int y = 0; y < 3; y++) (int x = 0; x < 3; x++) console.writeline("y={0}", test_descriptor[x,y]); }
sorting true 2d array difficult, because sorting algorithm must take account 2d structure of array. better off if you
- make plain array of size
tmp[m*n]
, - copy data
tmp
- sort
tmp
- copy sorted data original array
here how can it:
double tmp[test_descriptor.getlength(0)*test_descriptor.getlength(1)]; (int = 0; != test_descriptor.getlength(0); i++) { (int j = 0; j != test_descriptor.getlength(1); j++) { tmp[i*test_descriptor.getlength(1)+j] = test_descriptor[i, j]; } } array.sort(tmp); (int = 0; != test_descriptor.getlength(0); i++) { (int j = 0; j != test_descriptor.getlength(1); j++) { test_descriptor[i, j] = tmp[i*test_descriptor.getlength(1)+j]; } }
Comments
Post a Comment