1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| package Sort;
public class mergeSort { public static void main(String[] args) { int[] nums = {2,3,1,55,6,4,7,3,0}; int[] temp = new int[nums.length]; mergeSort(nums, temp, 0, nums.length - 1); for (int num : nums) { System.out.println(num); }
} public static void mergeSort(int[] nums, int[] temp, int start, int end) { if (start >= end) { return; } int left = start; int right = end; int mid = (start + end) / 2; mergeSort(nums, temp, left, mid); mergeSort(nums, temp, mid + 1, right); merge(nums, temp, start, mid, end); } public static void merge(int[] nums, int[] temp, int start, int mid, int end) { int leftIndex = start; int rightIndex = mid + 1; int index = start; while (leftIndex <= mid && rightIndex <= end) { if (nums[leftIndex] <= nums[rightIndex]) { temp[index++] = nums[leftIndex++]; } else { temp[index++] = nums[rightIndex++]; } } while (leftIndex <= mid) { temp[index++] = nums[leftIndex++]; } while (rightIndex <= end) { temp[index++] = nums[rightIndex++]; } for (int i = start; i <= end; i++) { nums[i] = temp[i]; } } }
|