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