Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.stream.Stream;
  3.  
  4. class MergeSortRecursive {
  5.  
  6. public String[] sort(String[] items) {
  7. int length = items.length;
  8. if(length <= 1) return items;
  9.  
  10. String[] left = sort(copy(items, 0, length/2));
  11. String[] right = sort(copy(items, length/2, length));
  12. return merge(left, right);
  13. }
  14.  
  15. public String[] merge(String[] list1, String[] list2) {
  16. int lenList1 = list1.length;
  17. int lenList2 = list2.length;
  18.  
  19. if(lenList1 <= 0) return list2;
  20. if(lenList2 <= 0) return list1;
  21.  
  22. if(list1[0].compareTo(list2[0]) <= 0)
  23. return concatenate(list1[0], merge(copy(list1, 1, lenList1), list2));
  24. else
  25. return concatenate(list2[0], merge(list1, copy(list2, 1, lenList2)));
  26. }
  27.  
  28. public final String[] concatenate(String list1, String[] list2) {
  29. return Stream.of(new String[]{list1}, list2)
  30. .flatMap(listArray -> Stream.of(listArray)).toArray(String[]::new);
  31. }
  32.  
  33. public final String[] copy(String[] items, int start, int endExclusive) {
  34. return Arrays.copyOfRange(items, start, endExclusive);
  35. }
  36.  
  37. public static void main(String[] args) {
  38. MergeSortRecursive mergesort = new MergeSortRecursive();
  39. String[] result = mergesort.sort(new String[]{"z", "a", "b", "t", "k", "m"});
  40. Stream.of(result).forEach(System.out::println);
  41. }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement