const listaLivros = require('./array');
const subLists = [];
const sortedSubLists = [];
subLists.push(listaLivros);
for(let i=0;i<subLists.length;i++){
if(subLists[i].length > 2){
splitList(subLists[i]);
i--;
}
else if(subLists[i].length === 2){
const list = subLists[i];
if(list[0].preco > list[1].preco){
list.push(list[0]);
list.splice(0,1);
}
sortedSubLists.push(subLists[i]);
}
else sortedSubLists.push(subLists[i]);
}
for(let i=0;i<sortedSubLists.length;i++){
if(i+1<sortedSubLists.length){
sortedSubLists.push(mergeSort(sortedSubLists[i],sortedSubLists[i+1]));
sortedSubLists.splice(0,2);
i--;
}
}
console.log(sortedSubLists[0]);
function mergeSort(listA,listB){
let i = 0;
let j = 0;
const C = [];
while(i<listA.length || j<listB.length){
if( j >= listB.length || (i < listA.length && listA[i].preco<listB[j].preco)){
C.push(listA[i]);
i++
}
else{
C.push(listB[j]);
j++
}
}
return C;
}
function splitList(list){
subLists.push(list.slice(0, Math.floor( (list.length/2) ) ) );
subLists.push(list.slice(Math.floor((list.length/2),list.length) ) );
subLists.splice(0,1);
}
Acho que consegui deixar o código bem simples, da pra entender?