0

私は宿題をしています。クイックソートを使用して文字列配列を並べ替える必要があり、配列内の要素は数値と文字列を組み合わせています。例えば

String s[];

s[0]="172,19,Nina";
s[1]="178,18,Apple";
s[2]="178,18,Alex";

したがって、並べ替えた後は、

s[0]=172,19,Nina
s[1]=178,18,Alex
s[2]=178,18,Apple

最初にすべての文字列を数値と文字列に分割し、次に172,178,178を並べ替え、次に19 18 18を並べ替え、最後にNina Apple Alexを並べ替える必要があると考えていますか?

これを行うための最良の方法は何ですか?

4

2 に答える 2

3

すべての数値の文字数が同じ場合、辞書式の順序は数値の順序と同じであるため、文字列を直接比較できます。

それ以外の場合は、文字列を分割し、Comparable インターフェイスを実装する適切なオブジェクトに変換する必要があります。

public class Record implements Comparable<Record> {
    private int firstNumber;
    private int secondNumber;
    private String name;

    ...

    @Override
    public int compareTo(Record r) {
        int result = Integer.valueOf(firstNumber).compareTo(Integer.valueOf(r.firstNumber);
        if (result != 0) {
            result = Integer.valueOf(secondNumber).compareTo(Integer.valueOf(r.secondNumber);
        }
        if (result != 0) {
            result = name.compareTo(r.name);
        }
        return result;
    }
}
于 2012-05-27T11:44:07.547 に答える
0

はい、その通りです。結合された文字列をその要素に分離し、これらの分離された要素に基づいて配列を並べ替える必要があります。最初の数値、次に 2 番目などに基づいて完全な配列を並べ替える必要はありませんが、それらに基づく比較ロジックを提供することに注意してください。これを字句順序と呼びます

基本的に、要素が別の要素よりも小さいかどうかを判断する必要がある場合、次のロジック (疑似コード) があります。

if elem1's first number < elem2's first number
then
  return elem1 less than elem2
else if elem1's first number > elem2's first number
then
  return elem1 greater than elem2
// from here on: elem1's first number == elem2's first number
else if elem1's second number < elem2's second number
then
  return elem1 less then elem2
else if elem1's second number > elem2's second number
then
  return elem1 greater than elem2
// from here on: elem1's second number == elem2's second number
else if elem1's third string < elem2's third string
then 
  return elem1 less then elem2
else if elem1's third string > elem2's third string
then
  return elem1 greater than elem2
else // everything is the same
  return elem1 equal elem2
于 2012-05-27T11:41:36.557 に答える