2012-03-19 99 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

相關問題