Advertisement
Guest User

Untitled

a guest
Mar 6th, 2015
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.68 KB | None | 0 0
  1.     public static void merge(Comparable[] a1, int left1, int right1, Comparable[] a2, int left2, int right2, Comparable[] a,int left) {
  2.     // Merge a1[left1...right1] and a2[left2...right2] into
  3.         // a[left...] (where both a1 and a2 are sorted).
  4.         int i = left1, j = left2, k = left;
  5.         while (i <= right1 && j <= right2) {
  6.         //both a1 and a2 contain elements to be merged
  7.             int comp = a1[i].compareTo(a2[j]);
  8.             if (comp <= 0) {
  9.         //a1 contains the smallest element, so it is copied //into the output array a
  10.             a[k++] = a1[i++];
  11.             }
  12.             else {
  13.         //a2 contains the smallest element, so it is copied
  14.         //into the output array a
  15.                 a[k++] = a2[j++];
  16.             }
  17.         }
  18.         while (i <= right1) {
  19.         // All elements in a2 have been sorted
  20.         //Copy the remainder elements from a1
  21.            a[k++] = a1[i++];
  22.         }
  23.         while (j <= right2) {
  24.         // All elements in a1 have been sorted
  25.         //Copy the remainder elements from a2
  26.             a[k++] = a2[j++];
  27.         }
  28.     }
  29.  
  30.     public void merge_sort(int left, int right) {
  31.         //Declare m
  32.         int m;
  33.        
  34.         //If left < right
  35.         if (left < right) {
  36.             //1.1 Let m be about midway between left and right.
  37.             m = (left + right) / 2;
  38.             //RECURSIVE PART//
  39.             //1.2 Sort a[left..m] into ascending order.
  40.             merge_sort(left, m);
  41.             //1.3 Sort a[m+1...right]
  42.             merge_sort(m + 1, right);
  43.             //1.4 Merge a[left..m] and a[m+1...right] into an auxiliary array
  44.             merge(left, m, right);
  45.         }
  46.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement