归并排序算法

22 阅读2分钟

归并排序算法

算法分为:

插入排序

交换排序

选择排序

归并排序

基数排序

一、基本思想

归并排序采用分治法思想,比如说有8个数据进行排序,

先将序列分成两个长度为4序列进行排序;

然后再将这两个长度为4的序列分为4个长度为2的子序列;

最后再将其分成为8个长度为1的子序列。

一般使用递归实现上面步骤,“分”的过程完成了,这时候就需要进行“合”了,如何进行合并呢?

先将前面的序列两两为一组进行合并,然后再4个为一组进行合并,最后再将两个长度为4的序列合并成1组。

二、程序实现

2.1、程序源代码

package com.bubaiwantong.sort;

/**
 *
 * 归并排序
 * @author 不败顽童
 */
public class MergeSort {
    public void MergeSort(int arr[],int tempArr[], int left, int right) {
        if (left < right) {
            int mid = (left + right) / 2;
            MergeSort(arr,tempArr, left, mid);
            MergeSort(arr,tempArr, mid + 1, right);
            merge(arr,tempArr, left, mid, right);
        }
    }

    public void merge(int arr[],int tempArr[], int leftBound, int mid, int rightBound) {
        for (int i = 0; i < rightBound - leftBound + 1; i++) {
            tempArr[i + leftBound] = arr[i + leftBound];
        }
        int left = leftBound, right = mid + 1, k = left;

        /*
            将左边的数据和右边的数据进行比较,小的数据使用k记录放入到arr[k]中,left从leftBound开始,到mid结束;right从mid+1开始,到rightBound结束。
         */
        while (left <= mid && right <= rightBound) {
            if (tempArr[left] < tempArr[right]) {
                arr[k++] = tempArr[left++];
            } else {
                arr[k++] = tempArr[right++];
            }
        }

        /*
            将tempArr中剩下的数据全部放到arr后面去
         */
        while (left <= mid) {
            arr[k++] = tempArr[left++];
        }
        while (right <= rightBound) {
            arr[k++] = tempArr[right++];
        }
    }


    public void printArr(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println("");
    }


    public static void main(String[] args) {
        int[] arr = new int[]{9, 8, 7, 6, 5, 4, 3, 2, 1};
        int[] tempArr = new int[arr.length];
        MergeSort mergeSort = new MergeSort();
        mergeSort.MergeSort(arr,tempArr, 0, arr.length - 1);
        mergeSort.printArr(arr);
    }

}

2.2、运行结果

1 2 3 4 5 6 7 8 9 

Process finished with exit code 0