问题
my professor has asked to sort a 2d char array by column so the attached array he wants sorted is
unsorted sorted last column
Lcekoeddhoffbmg Balgfcaelhfkgeb
Lkcmggjcdhhglif Kmlhmhcddfoeilc
Cgldjhcekjigcdd Cgldjhcekjigcdd
Cgldjhcekjigcdn Lkcmggjcdhhglif
Bffmdbkcenlafjk Lcekoeddhoffbmg
Fggdijijegfblln Jjlncnimjldfedj
Jjlncnimjldfedj Bffmdbkcenlafjk
Amliglfohajcdmm Amliglfohajcdmm
Balgfcaelhfkgeb Fggdijijegfblln
Kmlhmhcddfoeilc Cgldjhcekjigcdn
but the catch is that he wants the entire row to be the same characters so if we are sorting the last column we would just move the row up or down accordingly. i have no idea on how to even get this started any help would be much appreciated
回答1:
Assuming you know how to sort a 1d array (otherwise look it up), this is fairly similar.
Instead of swapping two chars (when you use bubble sort or any other sorting algorithm based on swapping items), you swap the two complete rows. So you get something like this (for bubble sort):
for char1 of each_last_row_char
for char2 of each_last_row_char_after_char1
if char2 < char2 then
swap rows of char1 and char 2
end
end
end
Swapping complete rows is not that difficult as well. You iterate over the amount of items in the rows (assuming they have the same amount of chars), and swap the items of both rows:
for index of row_items
tmp = row1[index]
row1[index] = row2[index]
row2[index] = tmp
end
Just like a regular swap implementation, but then for all items.
回答2:
You could convert each char array to a string then just use java's String sort functionality. then convert your strings back to char arrays.
来源:https://stackoverflow.com/questions/13851094/char-multidimensional-array-sorting-in-java