• 排序算法之递归算法(归并排序)


    归并排序实现原理:把一系列排好序的子序列合并成一个大的完整有序序列。在递归算法中归并排序算是一个比较典型的例子了,下面是使用javascript实现的归并排序算法:

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    <body>
        <script>
            var merge = function (unsorted, first, mid, last, sorted){
                var i = first, j = mid;
                var k = 0;
                while (i < mid && j < last){
                    if (unsorted[i] < unsorted[j])
                        sorted[k++] = unsorted[i++];
                    else
                        sorted[k++] = unsorted[j++];
                }
                while (i < mid){
                    sorted[k++] = unsorted[i++];
                }
                while (j < last){
                    sorted[k++] = unsorted[j++];
                }
    
                for (var v = 0; v < k; v++) {
                    unsorted[first + v] = sorted[v];  //   复制到原数组中
                }
            };
    
            var merge_sort = function (unsorted, first, last, sorted){
                if (first + 1 < last)
                {
                    var mid = Math.floor((first + last) / 2);
                    merge_sort(unsorted, first, mid, sorted);
                    merge_sort(unsorted, mid, last, sorted);
                    merge(unsorted, first, mid, last, sorted);
                }
            };
    
    //        var nums = [6,10,1,9,4,8,2,7,3,5];
            var nums = [6,2,8,3];
            var sorted = [];
            console.log("merge before 
    ");
            console.log(nums.toString());
            console.log("merge after 
    ");
            merge_sort(nums, 0, nums.length, sorted);
            console.log(nums.toString());
        </script>
    </body>
    </html>

    参考:http://www.cnblogs.com/jillzhang/archive/2007/09/16/894936.html

  • 相关阅读:
    ES进阶--01
    JVM--02
    JVM--01
    ES--08
    ES--07
    ES--06
    python实现当前主机ip 主机名称的获取
    djang中的blank=True 和null = True的区别
    python中yield的用法详解
    python 编写古诗赤壁赋
  • 原文地址:https://www.cnblogs.com/duhuo/p/5089820.html
Copyright © 2020-2023  润新知