2012-03-19 100 views
0

我的目标是编写一个方法,该方法需要2个字符串数组,并根据每个元素的长度对数组中的元素进行排序。通过使用合并排序?有没有更简单的方法来递归编写这段代码?

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

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))); 
    } 
} 

回答

1

sort静态方法调用它自己,是的,它是递归的。

它所做的事情,它所使用的语言以及所达到的效率,并非如此糟糕的代码。如果你想缩短,为什么不使用比较器和Arrays.sort?

(你可以保存在丑陋的合并代码数组访问里面的几行通过后递增变量)

+0

你能在这个代码看看这里,看看这可能是更好的 – user1276602 2012-03-19 04:07:34

+0

这段代码在哪里? – 2012-03-19 04:09:11

+0

您可以对此进行投票,以便我可以更改它 – user1276602 2012-03-19 04:13:54

相关问题