本文主要和大家分享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)
以上是js歸併演算法實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!