java归并排序模板

java实现归并排序模板

算法介绍

归并排序运用了递归的想法,又是分而治之,有“分”(将数组一分为二,分别排序两个子数组)和“治”(将子数组合并为目标数组)两部分,看代码就理解了。

代码模板

import java.util.Arrays;
import java.util.logging.LogRecord;
public class my {
    
    
    public static void main(String []args){
    
    
        int []arr = {
    
    9,8,7,6,5,4,3,2,1};
        sort(arr);
        System.out.println(Arrays.toString(arr));
    }
    public static void sort(int []arr){
    
    
        int []temp = new int[arr.length]; //创建一个临时数组来存排序过程中的结果
        sort(arr,0,arr.length-1,temp);
    }
    public static void sort(int []arr, int left, int right, int []temp){
    
    
        if (left < right){
    
    
            mid = (left + right) /2;
            sort(arr, left, mid, temp);
            sort(arr, left, mid + 1, temp);
            merge(arr, left, mid, right, temp);
        }
    }    
    public static void merge(int []arr, int left, int mid, int right, int []temp){
    
    
        int i = left; //左边指针
        int j = right; //右边指针
        int t = 0; //temp数组指针
        while(i <= mid && j <= right ){
    
    
            if (arr[i] <= arr[j]){
    
    
                temp[t++] = arr[i++];
            }
            else{
    
    
                temp[t++] = arr[j++];
            }
        }
        //将剩余的补到temp数组里
        while(i <= mid){
    
    
            temp[t++] = arr[i++];
        }
        while(j <= right){
    
    
            temp[t++] = arr[j++];
        }
    }
}

おすすめ

転載: blog.csdn.net/weixin_46235143/article/details/116898796