-3

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

spy-killer
  • 405
  • 4
  • 18

2 Answers2

0

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.

Magnus
  • 7,952
  • 2
  • 26
  • 52
  • This is assignment question. may be he is not allowed to use API. – Smit Dec 13 '12 at 00:42
  • This idea server to sort the matrix by entire rows, while OP needs *to sort a 2d char array by column*. Also, Java's `String` don't have a sort functionality, there are other APIs like `java.util.Arrays` or `java.util.Collections` to do this work, but since this looks like homework, I guess OP can't use any of these. – Luiggi Mendoza Dec 13 '12 at 00:55
0

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.

Veger
  • 37,240
  • 11
  • 105
  • 116
  • What part of *sort a 2d char array by column* haven't you read in the first line of the question? – Luiggi Mendoza Dec 13 '12 at 00:56
  • As I read it: the last chars of each row (ie the last column) are used to sort the rows. Which is exactly what my explanation and pseudo code aim for. – Veger Dec 13 '12 at 01:02