Created
February 17, 2017 18:38
-
-
Save TimCodes/453273d8f60487556f2cadf40f56d01f to your computer and use it in GitHub Desktop.
Revisions
-
TimCodes created this gist
Feb 17, 2017 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,71 @@ function MergSortEntry(arr){ // console.log(arr) let tempArr = []; let i = MergeSort(arr, tempArr, 0, arr.length - 1) //console.log(arr) return i } function MergeSort(arr, tempArr, leftStart, rightEnd ){ let invCount = 0; if( rightEnd > leftStart ){ let mid = parseInt( (leftStart + rightEnd) / 2 ); invCount += MergeSort(arr, tempArr, leftStart, mid); invCount += MergeSort(arr, tempArr, mid + 1, rightEnd); invCount += MergeAndCount(arr, tempArr, leftStart, mid + 1, rightEnd); } return invCount; } function MergeAndCount(arr, tempArr, leftIdx, midIdx, rightIdx){ let invCount = 0; let leftNewIdx = leftIdx // idx for left sub array let rightNewIdx = midIdx // idx for right sub array let tempIdx = leftIdx // idx for temp array while ( ( leftNewIdx <= midIdx - 1) && ( rightNewIdx <= rightIdx ) ){ if( arr[leftNewIdx] <= arr[rightNewIdx]){ tempArr[tempIdx] = arr[leftNewIdx]; leftNewIdx++; }else{ tempArr[tempIdx] = arr[rightNewIdx]; rightNewIdx++; invCount += (midIdx - leftNewIdx); // console.log('--- invcount temp--', invCount += (midIdx - leftNewIdx) ) } tempIdx++; } while( leftNewIdx <= midIdx - 1 ){ tempArr[tempIdx] = arr[leftNewIdx]; leftNewIdx++; tempIdx++; } while( rightNewIdx <= rightIdx ){ tempArr[tempIdx] = arr[rightNewIdx]; rightNewIdx++; tempIdx++; } for( var i = leftIdx; i <= rightIdx; i++){ arr[i] = tempArr[i]; } return invCount; } var a = [34, 203, 3, 746, 200, 984, 198, 764, 9]; var b = [2,1,3,1,2] //console.log( MergSortEntry(b)); //console.log( MergSortEntry(a));