Posted By

iTony on 11/10/08


Tagged

sort java merge algorithm


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

sergeizen


Merge-Sort function


 / Published in: Java
 

  1. public static void MergeSort(int[] array) {
  2. if(array.length>1){
  3. int elementsInA1=array.length/2;
  4. int elementsInA2=elementsInA1;
  5. if((array.length%2)==1)
  6. elementsInA2+=1;
  7.  
  8. int arr1[]=new int[elementsInA1];
  9. int arr2[]=new int[elementsInA2];
  10.  
  11. for(int i=0; i<elementsInA1; i++)
  12. arr1[i]=array[i];
  13.  
  14. for(int i=elementsInA1; i<elementsInA1+elementsInA2; i++)
  15. arr2[i-elementsInA1]=array[i];
  16.  
  17. MergeSort(arr1);
  18.  
  19. MergeSort(arr2);
  20.  
  21.  
  22. int i=0, j=0, k=0;
  23.  
  24. while(arr1.length!=j && arr2.length!=k){
  25. if(arr1[j]<=arr2[k]) {
  26. array[i]=arr1[j];
  27. j++;
  28. }else{
  29. array[i]=arr2[k];
  30. k++;
  31. }
  32. i++;
  33. }
  34.  
  35. while(arr1.length!=j){
  36. array[i]=arr1[j];
  37. i++;
  38. j++;
  39. }
  40. while(arr2.length!=k){
  41. array[i]=arr2[k];
  42. i++;
  43. k++;
  44. }
  45. }
  46. }

Report this snippet  

You need to login to post a comment.