Advertisement
Guest User

Untitled

a guest
May 23rd, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. public class MergeSort {
  2.  
  3. //归并排序两个有序链表
  4. public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  5. if (l1 == null) return l2;
  6. if (l2 == null) return l1;
  7. if (l1.val < l2.val) {
  8. l1.next = mergeTwoLists(l1.next, l2);
  9. return l1;
  10. } else {
  11. l2.next = mergeTwoLists(l1, l2.next);
  12. return l2;
  13. }
  14. }
  15.  
  16. //归并排序两个有序数组
  17. private static int[] mergeTwoArray(int[] left, int[] right) {
  18. int[] result = new int[left.length + right.length];
  19. int l = 0, r = 0;
  20. for (int index = 0; index < result.length; index++) {
  21. if (l >= left.length)
  22. result[index] = right[r++];
  23. else if (r >= right.length)
  24. result[index] = left[l++];
  25. else if (left[l] > right[r])
  26. result[index] = right[r++];
  27. else
  28. result[index] = left[l++];
  29. }
  30. return result;
  31. }
  32.  
  33. private static int[] mergeSort(int[] array) {
  34. if (array.length < 2) return array;
  35. int mid = array.length / 2;
  36. int[] left = Arrays.copyOfRange(array, 0, mid);
  37. int[] right = Arrays.copyOfRange(array, mid, array.length);
  38. return mergeTwoArray(mergeSort(left), mergeSort(right));
  39. }
  40.  
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement