分治法-归并排序

基本思路:将待排序元素分成大小大致相同的两个相同子集合,分别对两个子集合进行排序,最终将排好序的子集合合并成要求的排好序的集合。
分治法-归并排序_第1张图片

package com.algorithm;


public class MergeSort {

        public static void mergeSort1(Integer[] array){
            if(array == null || array.length < 2) {
                return;
            }
            sort(array,0,array.length-1);
        }


        public static void sort(Integer[] array,int l,int r) {
            if(l == r) {
                return;
            }
            int mid = l + (r-l)/2;
            sort(array,l,mid);
            sort(array,mid+1,r);
            merge(array,l,mid,r);
        }

        public static void merge(Integer[] array,int l,int mid,int r) {
            //生成一个临时数组,存储排好序的数组
            Integer[] temp = new Integer[r-l+1];
            int i = 0;
            int p1 = l;
            int p2 = mid+1;
            while (p1 <= mid && p2<=r ) {
                if(array[p1] < array[p2]) {
                    temp[i++] = array[p1++];//把小的数据放入数组
                } else {
                    temp[i++] = array[p2++];//把小的数据放入数组
                }
            }
            //将左边剩余的数据放入新数组
            while (p1 <= mid ) {
                temp[i++] = array[p1++];
            }

            //将右边剩余的数据放入新数组
            while (p2 <= r) {
                temp[i++] = array[p2++];
            }

            //排好序的新数组覆盖原数组
            for(int n = 0;n < temp.length;n++){
                array[n + l] = temp[n];
            }
        }



        public static void main(String[] args) {
            Integer[] array = new Integer[]{38,27,42,3,9,82,10};
            mergeSort1(array);
            System.out.println("排序后结果:");
            for(int arr:array) {
                System.out.print(arr+",");
            }
        }
}

你可能感兴趣的:(Data,Structure_JAVA,排序算法,算法,java,数据结构,开发语言)