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 53 54
| package 算法;
import java.util.Arrays;
public class 归并排序 {
public static void main(String[] args) { int[] nums = new int[]{6,2,1,5,3,4,9,8}; int[] temp = new int[nums.length]; sort(nums, 0,nums.length-1, temp); System.out.println(Arrays.toString(nums)); } private static void sort(int[] arr,int left,int right,int[] temp){ if(left<right){ int mid = (left+right)/2; sort(arr, left, mid,temp); sort(arr, mid+1, right,temp); merge(arr,left,mid,right,temp); } }
private static void merge(int[] arr,int left,int mid,int right,int[] temp) { int i = left; int j = mid+1; int index = 0; while(i<=mid&&j<=right){ if(arr[i]<arr[j]){ temp[index++] = arr[i++]; }else{ temp[index++] = arr[j++]; } } while(i<=mid){ temp[index++] = arr[i++]; } while(j<=right){ temp[index++] = arr[j++]; } index=0; while(left<=right){ arr[left++]=temp[index++]; } } }
|