归并排序

Posted mitsuhide1992

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了归并排序相关的知识,希望对你有一定的参考价值。

nodeJs实现

function mSort (list, low, high) 
    if (list == undefined || list.length == 0 || low >= high) 
        return;
    
    var mid = parseInt((low + high) / 2);
    mSort(list, low, mid);
    mSort(list, mid + 1, high);
    merge(list, low, mid, high);


function merge (list, low, mid, high) 
    var merged = [];
    for (var i = low, j = mid + 1, k = 0; i <= mid && j <= high; i++, j++) 
        if (list[i] < list[j])   
            merged[k++] = list[i++];  
         else   
            merged[k++] = list[j++];  
          
    

    while (i <= mid)   
        merged[k++] = list[i++];  
      

    // 把右边边剩余的数移入数组  
    while (j <= high)   
        merged[k++] = list[j++];  
      

    for (var k2 = 0; k2 < merged.length; k2++)   
        list[k2 + low] = merged[k2];  
      


var nums = [3, 8, 1, 6, 5, 4, 7, 2, 9, 0];
mSort(nums, 0, nums.length - 1);
for (var item in nums) 
    console.log(item);

Java实现

public class MergeSort 
    /*
    * 归并排序 list[low...high]
     */
    public void mergeSort (int [] list, int low, int high) 
        if (low < high) 
            int mid = low + (high - low) / 2;
            mergeSort(list, low, mid);
            mergeSort(list, mid + 1, high);
            merge(list, low, mid, high);
        
    

    /*
     * 把list[low...mid]和list[mid+1...high]合并成list[low...high]
     */
    public void merge (int [] list, int low, int mid, int high) 
        int [] merged = new int [high - low + 1];
        int i = low;
        int j = mid + 1;
        int k = 0;
        while (i <= mid && j <= high) 
            while (list[i] <= list[j] && i <= mid)
                merged[k++] = list[i++];
            while (list[i] > list[j] && j <= high)
                merged[k++] = list[j++];
        

        while (j <= high)
            merged[k++] = list[j++];

        while (i <= mid)
            merged[k++] = list[i++];

        for (k = 0; k <= high - low; k++) 
            list[low + k] = merged[k];
        
    

    public static void main (String [] args) 
        int [] list = 3,8,1,6,5,4,7,2,9;
        MergeSort ms = new MergeSort();
        ms.mergeSort(list, 0, list.length - 1);
        for (int item : list) 
            System.out.print(item + " ");
        
        System.out.println("");
    

以上是关于归并排序的主要内容,如果未能解决你的问题,请参考以下文章

归并排序

归并排序

6.6 归并排序

归并排序

归并排序

排序算法--归并排序