Summary of 2024 Pinduoduo campus recruitment interview questions and their answers (2)

6. [Algorithm question] Merge sort

Merge Sort is a divide-and-conquer algorithm that recursively divides the sequence to be sorted into two subsequences, and then merges the two ordered subsequences into one ordered sequence.

The algorithm flow of merge sort is as follows:

  1. Recursively divide the sequence to be sorted into two subsequences until each subsequence has only one element.
  2. Merge two ordered subsequences into one ordered sequence.

The code implementation of merge sort is as follows:

// 归并排序
public static void mergeSort(int[] arr) {
    if (arr.length <= 1) {
        return;
    }

    // 将待排序的序列分成两个子序列
    int mid = arr.length / 2;
    int[] left = Arrays.copyOfRange(arr, 0, mid);
    int[] right = Arrays.copyOfRange(arr, mid, arr.length);

    // 递归地排序两个子序列
    mergeSort(left);
    mergeSort(right);

    // 将两个有序的子序列合并成一个有序的序列
    merge(left, right, arr);
}

// 合并两个有序的子序列
private static void merge(int[] left, int[] right, int[] arr) {
    int i = 0, j = 0, k = 0;

    while (i < left.length && j < right.length) {
        if (left[i] < right[j]) {
            arr[k++] = left[i++];
        } else {
   

Supongo que te gusta

Origin blog.csdn.net/cq20110310/article/details/132866857
Recomendado
Clasificación