From d9a8742b6666340fc7be8e5064bb3637ed7a8b39 Mon Sep 17 00:00:00 2001 From: huxiaoran <3142657715@qq.com> Date: Thu, 6 Aug 2020 18:00:13 +0800 Subject: [PATCH] first commit --- MergeSort.java | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 MergeSort.java diff --git a/MergeSort.java b/MergeSort.java new file mode 100644 index 0000000..be422c8 --- /dev/null +++ b/MergeSort.java @@ -0,0 +1,61 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +/** + * + * @author lenovo + */ +public class MergeSort { + + private static int[] aux; + + public static void merge(int[] a, int low, int mid, int high) + { + int i = low; + int j = mid + 1; + + for(int k=low; k<=high; k++) + { + aux[k] = a[k]; + } + + for(int k=low; k<=high; k++) + { + if(i>mid) + { + a[k] = aux[j++]; + } + else if(j > high) + { + a[k] = aux[i++]; + } + else if (aux[j] < aux[i]) + { + a[k] = aux[j++]; + } + else + { + a[k] = aux[i++]; + } + } + } + + private static void sort(int[] a, int low, int high) + { + if(high <= low) return; + + int mid = low + (high - low) / 2; + sort(a, low, mid); + sort(a, mid+1, high); + merge(a, low, mid, high); + } + public void sort(int[] a) + { + int length = a.length; + aux = new int[length]; + sort(a, 0, length-1); + } +}