集册 Java实例教程 获取整数列表并使用merge sort对其排序并返回一个新数组

获取整数列表并使用merge sort对其排序并返回一个新数组

欢马劈雪     最近更新时间:2020-01-02 10:19:05

655
获取整数列表并使用merge sort对其排序并返回一个新数组

/** 
来 自 
时代Java公众号 - N o w J a  v a . c o m
**/

//package com.nowjava;


public class Main {

    /**

     * This function takes a list of integers and uses merge sort to sort them

     * and returns a new array

     * @param list

     * @return

     */

    public static Integer[] mergeSort(Integer[] list) {

        if (list.length == 1)

            return list;

        int middle = list.length / 2;

        Integer[] left = new Integer[middle];

        for (int x = 0; x < middle; x++)

            left[x] = list[x];

        //System.out.print("left:"); printArray(left);

        Integer[] right = new Integer[list.length - middle];
        /*
        时代Java公众号 提供
        */

        for (int x = 0; x < list.length - middle; x++)

            right[x] = list[middle + x];

        //System.out.print("right:"); printArray(right);

        return merge(mergeSort(left), mergeSort(right));

    }


    /**

     * This function merges two already sorted lists (in ascending order)

     * Approach:

     *    - just keeps two pointers and moves pointer along for whichever

     * list is being used to create the new list

     * @param list1

     * @param list2

     * @return

     */

    public static Integer[] merge(Integer[] list1, Integer[] list2) {

        int ptr1 = 0;

        int ptr2 = 0;

        int i = 0;

        Integer[] combined = new Integer[list1.length + list2.length];

        /*System.out.println("Combining ->");

           System.out.print("list 1:"); printArray(list1);

           System.out.print("list 2:"); printArray(list2);*/

        while (ptr1 < list1.length || ptr2 < list2.length) {

            if (ptr1 >= list1.length) {

                combined[i] = list2[ptr2];

                ptr2++;

            } else if (ptr2 >= lis
展开阅读全文