Guest User

Untitled

a guest
Mar 23rd, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. public int[] mergeSort(int[] array) {
  2. if (array.length == 1) return array;
  3.  
  4. int start = 0;
  5. int end = array.length;
  6. int middle = (end-start)/2;
  7.  
  8. int[] left = Arrays.copyOfRange(array, start, middle);
  9. int[] right = Arrays.copyOfRange(array, middle, end);
  10.  
  11. int[] sortedLeft = mergeSort(left);
  12. int[] sortedRight = mergeSort(right);
  13.  
  14. return merge(sortedLeft, sortedRight);
  15. }
  16.  
  17. private int[] merge(int[] first, int[] second) {
  18. int[] result = new int[first.length + second.length];
  19.  
  20. int posFirst = 0;
  21. int posSecond = 0;
  22. int posResult = 0;
  23.  
  24. while (posResult < result.length) {
  25. if (posFirst == first.length) {
  26. result[posResult++] = second[posSecond++];
  27. }
  28. else if (posSecond == second.length) {
  29. result[posResult++] = first[posFirst++];
  30. }
  31. else if (first[posFirst] > second[posSecond]) {
  32. result[posResult++] = second[posSecond++];
  33. } else {
  34. result[posResult++] = first[posFirst++];
  35. }
  36. }
  37. return result;
  38. }
Add Comment
Please, Sign In to add comment