Advertisement
arsovski

mergeSortWithoutCopy

Oct 19th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. private static void mergeSort(int[] arr,int begin,int end){
  2.  
  3.  
  4. if(begin>=end)
  5. return;
  6.  
  7. int middle=(begin + end)/2;
  8. mergeSort(arr,begin,middle);
  9. mergeSort(arr,middle+1,end);
  10. merge(arr,begin,middle,end);
  11.  
  12. }
  13.  
  14. private static void merge(int[] arr,int begin,int middle,int end){
  15.  
  16. int firstContainerLimit=middle-begin+1;
  17. int[] firstContainer=new int[firstContainerLimit];
  18.  
  19. int secondContainerLimit=end-middle;
  20. int[] secondContainer=new int[secondContainerLimit];
  21.  
  22. //copy to first container
  23.  
  24. for(int i=0;i<firstContainerLimit;i++)
  25. firstContainer[i]=arr[begin+i];
  26.  
  27. for(int i=0;i<secondContainerLimit;i++)
  28. secondContainer[i]=arr[middle+1+i];
  29.  
  30.  
  31. int i=0;
  32. int j=0;
  33. int k=begin;
  34. while(i< firstContainerLimit && j<secondContainerLimit){
  35.  
  36. if(firstContainer[i] <= secondContainer[j]){
  37. arr[k++]=firstContainer[i];
  38. i++;
  39. }
  40. else{
  41. arr[k++]=secondContainer[j];
  42. j++;
  43. }
  44.  
  45. }
  46.  
  47. while(i<firstContainerLimit)
  48. arr[k++]=firstContainer[i++];
  49.  
  50. while(j<secondContainerLimit)
  51. arr[k++]=secondContainer[j++];
  52.  
  53.  
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement