集册 Java实例教程 合并排序的Java实现

合并排序的Java实现

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

540
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
合并排序的Java实现
/**
 from
* n o w j a v a . c o m 
**/

class Merge_Sort

{

    public static int temp[];


    // Conquer

    public static void conquer_merge(int[] array, int left, int right, int mid)

    {

        int k = left, i, j;


        for(i = left, j = mid + 1; i <= mid && j <= right; k++)

        {

            if(array[i] <= array[j])

            {

                temp[k] = array[i];

                i++;

            }

            else

            {

                temp[k] = array[j];

                j++;

            }/**nowjava - 时代Java**/

        }


        while(i <= mid)

        {

            temp[k] = array[i];

            i++;

            k++;

        }


        while(j <= right)

        {

            temp[k] = array[j];

            j++;

            k++;

        }


        for(i = left; i <= right; i++)

            array[i] = temp[i];

    }


    // Divide array into halves

    public static void divide(int[] array, int left, int right)

    {

        if(left < right)

        {

            int mid = left + (right - left) / 2;


            divide(array, left, mid);

            divide(array, mid + 1, right);


            conquer_merge(array, left, right, mid);

        }

    }


    public static void MergeSort(int array[], int size)

    {

        temp = new int[size];

        divide(array, 0, size - 1);

        temp = null;

    }


    // function ro print array

    public static void Print_Array(int[] array, int size)

    {

        for(int i = 0; i < size; i++)

            
展开阅读全文