码迷,mamicode.com
首页 > 编程语言 > 详细

递归算法(归并排序)

时间:2015-12-30 21:36:16      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

归并排序实现原理:把一系列排好序的子序列合并成一个大的完整有序序列。在递归算法中归并排序算是一个比较典型的例子了,下面是使用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 \n");
        console.log(nums.toString());
        console.log("merge after \n");
        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

 

递归算法(归并排序)

标签:

原文地址:http://www.cnblogs.com/duhuo/p/5089820.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!