Rumah >hujung hadapan web >tutorial js >js归并算法实例详解
本文主要和大家分享js归并算法实例详解,希望能帮助到大家。
将数组递归分裂成单个元素 然后合并数组
let data3 = [14, 54, 73, 38, 39, 67, 75, 80, 50, 40, 96, 27, 105, 109, 77, 31]function breakArr (data,start,end) { if (start < end) { let mid = Math.floor((start + end)/2) breakArr(data,start,mid) breakArr(data,mid+1,end) combineArr(data,start,mid,end) } } function combineArr(data,start,mid,end){ let i = start,j=mid+1; let m = mid, n=end; let k = 0; let temp = [] while(i<=m && j<=n) { if (data[i]<=data[j]) temp[k++] = data[i++] else temp[k++] = data[j++] } while(i<=m) temp[k++] = data[i++]; while(j<=n) temp[k++] = data[j++]; for ( i = 0; i < k; i++) { data[start + i] = temp[i] } console.log(temp) } breakArr(data3,0,15)
Atas ialah kandungan terperinci js归并算法实例详解. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!