Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static void mergeSort(double [] array, int first, int last) {
- if (first < last) {
- int middle = (first+last) / 2; // Get middle element of array
- mergeSort(array, first, middle); // Sort left side of the array
- mergeSort(array, middle + 1, last); // Sort right side of the array
- merge(array, first, middle, last); // Combine both sides
- }
- }
- public static void merge(double [] array,int first, int middle, int last) {
- // Copy both parts into the helper array
- double [] temp = new double [array.length];
- for (int i = first; i <= last; i++) {
- temp[i] = array[i];
- }
- int i = first;
- int j = middle + 1;
- int k = first;
- // Copy the smallest values from left or right side back into original array
- while (i <= middle && j <= last) {
- if (temp[i] <= temp[j]) {
- array[k] = temp[i];
- i++;
- } else {
- array[k] = temp[j];
- j++;
- }
- k++;
- }
- // Copy the rest of the left side of the array back into original array
- while (i <= middle) {
- array[k] = temp[i];
- k++;
- i++;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement