是否有一种更简单的方法来递归地编写这段代码?

时间:2012-03-19 03:52:36

标签: java

我的目标是编写一个方法,该方法采用2个String数组,并按照每个元素的长度对数组中的元素进行排序。使用合并排序???

这是我的代码,但我希望它更加浓缩,我不知道这段代码是否是递归的。

import java.util.Arrays;
import java.util.Comparator;

public class Test {

    private static Comparator<String> COMP = new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            if(o1.length() < o2.length()) {
                return -1;
            }
            if(o1.length() > o2.length()) {
                return 1;
            }
            return o1.compareToIgnoreCase(o2);
        }
    };

    public static String[] mergeUnsorted(String[] arr1, String[] arr2) {
        arr1 = sort(arr1);
        arr2 = sort(arr2);

        return merge(arr1, arr2);
    }

    private static String[] sort(String[] arr) {
        if(arr.length <= 1)
            return arr;

        String[] left = Arrays.copyOfRange(arr, 0, arr.length/2);
        String[] right = Arrays.copyOfRange(arr, arr.length/2, arr.length);

        left = sort(left);
        right = sort(right);

        String[] combined = merge(left, right);

        return combined;
    }

    private static String[] merge(String[] arr1, String[] arr2) {
        String[] combined = new String[arr1.length + arr2.length];

        int a = 0, b = 0, i = 0;

        while(a < arr1.length || b < arr2.length) {
            int compare = 0;
            if(a >= arr1.length) {
                compare = 1;
            } else if(b >= arr2.length) {
                compare = -1;
            } else {
                compare = COMP.compare(arr1[a], arr2[b]);
            }

            if(compare < 0) {
                combined[i] = arr1[a];
                i++;
                a++;
            } else if(compare > 0) {
                combined[i] = arr2[b];
                i++;
                b++;
            } else {
                combined[i] = arr1[a];
                i++;
                a++;
                combined[i] = arr2[b];
                i++;
                b++;
            }
        }

        return combined;
    }

    public static void main(String[] args) {
        String[] arr1 = new String[] { "abc", "a", "A", "bA", "Ba" };
        String[] arr2 = new String[] { "def", "d", "D", "fG", "Fg", "abcde", "B" };

        System.out.println(Arrays.toString(mergeUnsorted(arr1, arr2)));
    }
}

0 个答案:

没有答案