使用组合数字和字符串的元素来排序字符串数组

时间:2012-05-27 11:35:48

标签: java quicksort

我正在做我的作业,我需要使用快速排序来排序字符串数组,以及数组中的元素组合数字和字符串。例如

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

我想我应该首先将所有Strings分成数字和字符串,然后排序172,178,178,然后排序19 18 18,最后排序Nina Apple Alex ??

这样做的最佳方式是什么?

2 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分: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