标签:blog http io java ar for 2014 div 问题
上篇文章讲到插入排序算法,是一个标准的增量方法:在排好的子数组后,将元素插入,形成新的数组。今天要介绍的是一种新方法:分治法。
merge(A, p, q, r) n1=q-p+1 n2=r-q L R = [] for i=1->n1 L[i]=A[p+i-1] for j=1>n2 R[j]=A[q+j] L[n1+1]=Infinity R[n2+1]=Infinity for k=p->r if L[i]<=R[i] A[k]=L[i] i++ else A[k]=R[j] j++
mergeSort(A, p, r) if p < r q = parseInt((p+r)/2) mergeSort(A, p, q) mergeSort(A,q+1,r) merge(A,p,q,r);
var ARR = [5,2,4,7,1,3,2,6]; function merge(arr, p, q, r) { var n1 = q - p + 1; var n2 = r - q; var L = []; var R = []; for(var i = 1; i <= n1; i++) { L[i] = arr[p+i-1]; } for(var j = 1; j <= n2; j++) { R[j] = arr[q+j]; } L[n1 + 1] = Infinity; R[n2 + 1] = Infinity; i = j = 1; for(var k = p; k <= r; k++) { if(L[i] <= R[j]) { arr[k] = L[i]; i++; }else { arr[k] = R[j]; j++; } } return arr; } function mergeSort(arr, p, r) { if(p < r) { var q = Math.floor((p+r)/2); mergeSort(arr, p, q); mergeSort(arr, q+1, r); return merge(arr, p, q, r); } } console.log(mergeSort(ARR, 0, ARR.length-1));
标签:blog http io java ar for 2014 div 问题
原文地址:http://www.cnblogs.com/xiaoheimiaoer/p/3971335.html