Advertisement
vaskell

Merge Sort

Nov 6th, 2013
910
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.17 KB | None | 0 0
  1. public static void mergeSort(double [] array, int first, int last) {
  2.  
  3.         if (first < last) {
  4.             int middle = (first+last) / 2; // Get middle element of array
  5.             mergeSort(array, first, middle); // Sort left side of the array
  6.             mergeSort(array, middle + 1, last); // Sort right side of the array
  7.             merge(array, first, middle, last); // Combine both sides
  8.         }
  9.     }
  10.    
  11. public static void merge(double [] array,int first, int middle, int last) {
  12.  
  13.         // Copy both parts into the helper array
  14.           double [] temp = new double [array.length];
  15.         for (int i = first; i <= last; i++) {
  16.           temp[i] = array[i];
  17.         }
  18.  
  19.         int i = first;
  20.         int j = middle + 1;
  21.         int k = first;
  22.         // Copy the smallest values from left or right side back into original array
  23.  
  24.         while (i <= middle && j <= last) {
  25.           if (temp[i] <= temp[j]) {
  26.             array[k] = temp[i];
  27.             i++;
  28.           } else {
  29.             array[k] = temp[j];
  30.             j++;
  31.           }
  32.           k++;
  33.         }
  34.         // Copy the rest of the left side of the array back into original array
  35.         while (i <= middle) {
  36.           array[k] = temp[i];
  37.           k++;
  38.           i++;
  39.         }
  40.  
  41.       }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement