Mesclar duas matrizes e classificar a final
Em uma entrevista, me fizeram a seguinte pergunta. Recebi duas matrizes, ambas são classificadas.
MAS
A matriz 1 terá alguns -1 e a matriz 2 terá números totais como o número total de -1 na matriz 1.
Portanto, no exemplo abaixo, array1 possui três -1, portanto, array2 possui 3 números.
deixe dizer
var arrayOne = [3,6,-1,11,15,-1,23,34,-1,42];
var arrayTwo = [1,9,28];
As duas matrizes serão classificadas.
Agora eu tenho que escrever um programa que mesclará arrayTwo em arrayOne substituindo -1's, e arrayOne deve estar na ordem classificada.
Então a saída será
arrayOne = [ 1,3, 6, 9, 11, 15, 23, 28 ,34, 42 ]
A classificação deve ser feita sem o uso de qualquer API de classificação.
Eu escrevi um código a seguir
function puzzle01() {
var arrayOne = [3, 6, -1, 11, 15, -1, 23, 34, -1, 42];
var arrayTwo = [1, 9, 28];
var array1Counter = 0,
isMerged = false;
console.log(" array-1 ", arrayOne);
console.log(" array-2 ", arrayTwo);
for (var array2Counter = 0; array2Counter < arrayTwo.length; array2Counter++) {
isMerged = false;
while (isMerged === false && array1Counter < arrayOne.length) {
if (arrayOne[array1Counter] === -1) {
arrayOne[array1Counter] = arrayTwo[array2Counter];
isMerged = true;
}
array1Counter++;
}
} //for
console.log(" array-1 + array-2 ", arrayOne);
bubbleSort(arrayOne);
console.log(" Sorted array ", arrayOne);
} //puzzle01
puzzle01();
// implementation of bubble sort for sorting the
// merged array
function bubbleSort(arrayOne) {
var nextPointer = 0,
temp = 0,
hasSwapped = false;
do {
hasSwapped = false;
for (var x = 0; x < arrayOne.length; x++) {
nextPointer = x + 1;
if (nextPointer < arrayOne.length && arrayOne[x] > arrayOne[nextPointer]) {
temp = arrayOne[x];
arrayOne[x] = arrayOne[nextPointer];
arrayOne[nextPointer] = temp;
hasSwapped = true;
}
} //for
} while (hasSwapped === true);
} // bubbleSort
A saída do código acima é
array-1 [ 3, 6, -1, 11, 15, -1, 23, 34, -1, 42 ]
array-2 [ 1, 9, 28 ]
array-1 + array-2 [ 3, 6, 1, 11, 15, 9, 23, 34, 28, 42 ]
Sorted array [ 1, 3, 6, 9, 11, 15, 23, 28, 34, 42 ]
A partir do código acima, você pode ver, primeiro mesclei as duas matrizes e depois classifiquei a final.
Só queria saber, existe uma solução melhor.
Existe alguma falha na minha solução.
Por favor, deixe-me saber, será útil.
Depois de ler todos os seus comentários e respostas muito úteis, descobri que era capaz de descobrir uma solução mais rápida.
Vamos dar um exemplo
var arrayOne = [3,6,-1,11,15,-1,32,34,-1,42,-1];
var arrayTwo = [1,10,17,56],
Passo 1: Iterarei através do arrayTwo. Pegue o próximo elemento (ou seja, '1') e compare com o próximo elemento de arrayOne (ou seja, '3') e compare.
Etapa 2a: Se o elemento da matriz1 for maior que o elemento da matriz2 do que os elementos da matriz de swap. Agora vá para o próximo elemento do array1.
OU
etapa 2b: se o elemento da matriz1 for igual a -1 que os elementos da matriz de troca. Agora vá para o próximo elemento do array2.
etapa 3: vá para a etapa 1.
assim
no exemplo acima
primeira iteração, array1 = [1,6, -1,11, ...] array2 = [3,10,17,56]
segunda iteração, array1 = [1,3, -1,11, ..] array2 = [6,10,17,56]
terceira iteração, array1 = [1,3,6,11 ..] array2 = [-1,10,17,56]
quarta iteração array1 = [1,3,6,10, ..] array2 = [-1,11,17,56]
e assim por diante.
no final eu vou pegar a saída
array1 = [ 1, 3, 6, 10, 11, 15, 17, 32, 34, 42, 56 ]
array2 = [-1,-1,-1]
Encontre o código abaixo,
function puzzle02(arrayOne,arrayTwo){
var array1Counter = 0,
array2Counter = 0,
hasMinusOneOccurred = false;
console.log(" array-1 ",arrayOne);
console.log(" array-2 ",arrayTwo);
while(array2Counter < arrayTwo.length){ // iterate through array2
do{
if(arrayOne[array1Counter] === -1){ // if -1 occurred in array1
hasMinusOneOccurred = true;
// swaping numbers at current position of array1
// with current position of array2
swap(arrayOne,arrayTwo,array1Counter,array2Counter);
// recheck if the current value is greater than other values
// of array1
if(recheckAndSort(arrayOne,array1Counter) === true){
array1Counter = -1;// recheck array1 from start
}else{
// recheck the current array1 counter, for doing so go 1 count back
// so that even if the counter is incremented it points to current
// number itself
array1Counter--;
}
}else if(arrayOne[array1Counter] > arrayTwo[array2Counter]){
swap(arrayOne,arrayTwo,array1Counter,array2Counter);
}else{
array1Counter++;
continue;
}
array1Counter++;
}while(hasMinusOneOccurred === false); // end of do-while
array2Counter++;
hasMinusOneOccurred = false;
}//end of while
console.log(" Sorted array ",arrayOne);
function swap(arr1,arr2,arr1Index,arr2Index){
var temp = arr2[arr2Index];
arr2[arr2Index] = arr1[arr1Index];
arr1[arr1Index] = temp;
}// end of swap
// this method is call if -1 occures in array1
function recheckAndSort(arrayOne,array1Counter){
var isGreaterVal = true,
prevCounter = 0,
nextCounter = 0,
temp = 0,
recheckFromStart = false;
if(array1Counter === 0){ // if -1 occurred at first position of array1.
// flag to check if -1 occurrec at first position
// if yes, iterate array1 from start
recheckFromStart = true;
// iterate forward to check wether any numbers are less than current position,
// if yes than move forward
for(var j = 0; isGreaterVal; j++){
nextCounter = j + 1;
if(arrayOne[nextCounter] === -1){
// swaping numbers of array1 between next to current
swap(arrayOne,arrayOne,nextCounter,j);
isGreaterVal = true;
}else if(arrayOne[nextCounter] < arrayOne[j]){
// swaping numbers of array1 between next to current
swap(arrayOne,arrayOne,nextCounter,j);
isGreaterVal = true;
}else{
isGreaterVal = false;
}
}//end of for
}else{// if -1 occurred in the middle position of array1 and is been swaped then
// iterate backwards to check if any number less then current position exists,
// if yes than shift backwards.
for(var i = array1Counter; isGreaterVal; i--){
prevCounter = i - 1;
if(arrayOne[prevCounter] > arrayOne[i]){
// swaping numbers of array1 between previous to current
swap(arrayOne,arrayOne,prevCounter,i);
isGreaterVal = true;
}else{
isGreaterVal = false;
}
}// end of for
}
return recheckFromStart;
}// end of recheckAndSort
} // end of puzzle02
Depois de chamar a função acima
puzzle02([3,6,-1,11,15,-1,32,34,-1,42,-1],[1,10,17,56]);
A saída do código acima é,
array-1 [ 3, 6, -1, 11, 15, -1, 32, 34, -1, 42, -1 ]
array-2 [ 1, 10, 17, 56 ]
Sorted array [ 1, 3, 6, 10, 11, 15, 17, 32, 34, 42, 56 ]
Obrigado.