Reputation: 6166
Having this array:
const myArry = [1, 543, 0, 232, 1, 45654, -5, 0, 7, 4, 0, 43, 77, 0, 77, 0]
It must be sorted in ascending order and place all 0
s at the end, so the output should be:
[-5, 1, 1, 4, 7, 43, 77, 77, 232, 543, 45654, 0, 0, 0, 0, 0]
For sorting it's straightforward:
function sorting(arr) {
for(let i = 0; i< arr.length; i++) {
for (let j = 0; j < arr.length - i -1; j++) {
if(arr[j+1] < arr[j]) {
[arr[j+1], arr[j]]=[arr[j], arr[j+1]];
}
}
}
return arr;
}
But for moving those 0
s I cannot find a solution to do it without native functions like push
:
function moveZeros(arr) {
let newArray = [];
let counter = 0;
for (let i = 0; i < arr.length; i++) {
if(arr[i] !== 0) {
newArray.push(arr[i]);
}
else { counter++; }
}
for (let j = 0; j < counter; j++) {
newArray.push(0);
}
return newArray;
}
Is there a way to do this? Also, if combining both methods into one
Upvotes: 2
Views: 50
Reputation: 2312
You can do it with the sort
function. It s much readable.
myArry.sort((a, b) => {
if(b === 0) return -Infinity;
if(a === 0) return Infinity;
return a -b
})
Upvotes: 1
Reputation: 1285
When sorting numbers, to move all zeroes to the end, you have to give it more weight than any other number. Here, I "edge-cased" zero to always swap such that it moves to the end.
const myArry = [1, 543, 0, 232, 1, 45654, -5, 0, 7, 4, 0, 43, 77, 0, 77, 0]
function sorting(arr) {
for(let i = 0; i< arr.length; i++) {
for (let j = 0; j < arr.length - i -1; j++) {
if(arr[j+1] < arr[j] && arr[j+1] != 0 || arr[j] == 0) {
[arr[j+1], arr[j]]=[arr[j], arr[j+1]];
}
}
}
return arr;
}
console.log('' + sorting(myArry))
Upvotes: 3