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

是的,您是对的:您需要将组合字符串分成其元素,并根据这些分离的元素对数组进行排序。请注意,您不需要根据第一个数字对整个数组进行排序,然后是第二个等,而是提供基于它们的比较逻辑。这称为词法排序

基本上,当您需要确定一个元素是否小于另一个元素时,您有以下逻辑(伪代码):

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 回答