归并排序 --- Java版

算法思路

mergeSort.jpg
  1. 把待排序List中间切分成2段,而且是递归切分,直到子List元素只有1个结束。
  2. 把切分好的子List,进行按照大小进行排序merge,合成一个List。
  3. 重复这个过程,直到形成一个完整的排序好的List。


算法实现

class TestClass {
    public static void main(String args[] ) throws Exception {
        /* Sample code to perform I/O:
         * Use either of these methods for input

        //BufferedReader
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String name = br.readLine();                // Reading input from STDIN
        System.out.println("Hi, " + name + ".");    // Writing output to STDOUT

        //Scanner
        Scanner s = new Scanner(System.in);
        String name = s.nextLine();                 // Reading input from STDIN
        System.out.println("Hi, " + name + ".");    // Writing output to STDOUT

        */

        // Write your code here
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();                 // Reading input from STDIN
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = s.nextInt();
        }
        
        mergeSort(a, 0, n - 1);
        for (int i = 0; i < n; i++) {
            System.out.printf("%d ", a[i]);
        }
    }
    
    private static void mergeSort(int[] a, int low, int high) {
        if (low >= high) {
            return;
        }
        
        int mid = low + (high - low) / 2;
        mergeSort(a, low, mid);
        mergeSort(a, mid + 1, high);
        
        merge(a, low, mid, high);
    }
    
   private static void merge(int[] a, int low, int mid, int high) {

        int[] nums = new int[high - low + 1];
        // 合并的第一个数组起始位置p
        // 合并的第二个数组起始位置q
        int p = low, q = mid + 1;
        int index = 0;
        while (p <= mid && q <= high) {
            if (a[p] < a[q]) {
                nums[index++] = a[p++];
            } else {
                nums[index++] = a[q++];
            }
        }

        while (p <= mid) {
            nums[index++] = a[p++];
        }

        while (q <= high) {
            nums[index++] = a[q++];
        }

        System.arraycopy(nums, 0, a, low, high - low + 1);
    }

你可能感兴趣的:(归并排序 --- Java版)