suppose we have an array of objects with one property called cat.
How can we sort this array alternating the values based on the value of cat property on an efficient and cleaver way? suppose category value is always 'a' or 'b'.
given:
[
{cat: 'a'}, {cat: 'b'},
{cat: 'b'}, {cat: 'a'},
{cat: 'b'}, {cat: 'b'},
{cat: 'b'}, {cat: 'b'},
{cat: 'b'}, {cat: 'a'}
]
expected output:
[
{ cat: 'a' },
{ cat: 'b' },
{ cat: 'a' },
{ cat: 'b' },
{ cat: 'a' },
{ cat: 'b' },
{ cat: 'b' },
{ cat: 'b' },
{ cat: 'b' },
{ cat: 'b' }
]
I implemented the solution bellow, but it seens quite strange:
let myArr = [
{cat: 'a'}, {cat: 'b'},
{cat: 'b'}, {cat: 'a'},
{cat: 'b'}, {cat: 'b'},
{cat: 'b'}, {cat: 'b'},
{cat: 'b'}, {cat: 'a'}
]
alternatedSort = (it, i, arr) => {
function findAlternatedValueIndex(lookupIndex, it, arr){
if(lookupIndex < arr.length && arr[lookupIndex].cat == it['cat']){
lookupIndex ++
return findAlternatedValueIndex(lookupIndex, it, arr)
}
else
return lookupIndex < arr.length ? lookupIndex : undefined
}
var lookupIndex = i + 1
if (lookupIndex < arr.length && arr[lookupIndex].cat == it['cat']){
let tgtIndex = findAlternatedValueIndex(lookupIndex, it, arr)
if (tgtIndex) {
const aux = arr[lookupIndex]
arr[lookupIndex] = arr[tgtIndex]
arr[tgtIndex] = aux
}
}
}
myArr.forEach(function(it, i, arr) {
alternatedSort(it,i, arr)
});
console.log("sorted array: ", myArr)
obs: what is the complexity of the algorithm above and what is the best complexity we could get?