算法学习:二、归并排序

合并数组子方法的伪代码:

数组A[p..q] and A[q+1..r];total number is (r - p +1).
MERGE(A, p, q, r)
n1 = q - p + 1
n2 = r - q
let L[1..n1 + 1] and R[1..n2 + 1] be new arrays
for i = 1 to n1
    L[i] = A[p + i -1]
for j = 1 to n2
    R[j] = A[q + j]
L[n1 + 1] = infinity            //flag
R[n2 + 1] = infinity            //flag
i = 1
j = 1
for k = p to r
    ifL[i] <= R[j]
        A[k] = L[i]
        i = i + 1
    else
        A[k] = R[j]
        j = j + 1
        

归并排序算法的伪代码:

MERGESORT(A, p, r)
    if p < r
       q = (p + r)/2       //向下取整
        MERGESORT(A,p,q)
        MERGESORT(A,q+1,r)
        MERGE(A,p,q,r)

归并排序java代码:

package mergeSort;

/**
 * @Author: Wang
 * @Date:Created in 23:21 2020/3/15
 * @Modify By:
 */
public class MergeSort {

    public static void main(String[] args) {
        int[] nums =new  int[]{20,10,45,32,15,89,96,102};
        mergeSort(nums, 0, nums.length - 1);
        for (int i = 0; i < nums.length; i++) {
            System.out.println(nums[i]);
        }
    }

    private static void mergeSort(int[] nums, int p, int r) {
        if (p < r) {
            int q = (p + r) / 2;
            mergeSort(nums, p, q);
            mergeSort(nums, q + 1, r);
            merge(nums,p,q,r);
        }
    }

    private static void merge(int[] nums, int p, int q, int r) {
        int n1 = q - p + 1;
        int n2 = r - q;
        int[] L1 = new int[n1 + 1];
        int[] L2 = new int[n2 + 1];
        for (int i = 0; i < n1; i++) {
            L1[i] = nums[p + i];
        }
        L1[n1] = Integer.MAX_VALUE;
        L2[n2] = Integer.MAX_VALUE;
        for (int j = 0; j < n2; j++) {
            L2[j] = nums[q + j + 1];
        }
        int i = 0;
        int j = 0;
        for (int k = p; k <= r; k++) {
            if (L1[i] <= L2[j] && i < n1 ) {
                nums[k] = L1[i];
                i++;
            } else if (j < n2){
                nums[k] = L2[j];
                j++;
            }
        }

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值