The JavaScript array is sorted in odd and even numbers, with the odd number first and the even number last. No new array is required.

for example: [1, 2, 3, 4, 5] after sorting: 1, 3, 5, 2, 4
Note: does not create a new array , that is, it is changed on the basis of the original array.

May.22,2021

if the order between odd numbers and even numbers does not need to be consistent with the original, you can refer to the idea of fast row
A pointer searches from left to right, a pointer searches from right to left, when the left finds an even number, and when the right finds an odd number, swap two numbers, and then continue to search until the two pointers are the same


Bubble sort

let arr = [1, 2, 3, 4, 5, 7, 9, 10, 13, 18];

for (let i = 0; i < arr.length - 1; iPP) {
    for (let j = 0; j < arr.length - i - 1; jPP) {
        let tmp = arr[j];
        if (tmp % 2 === 0 && arr[j + 1] % 2 !== 0) {
            arr[j] = arr[j + 1];
            arr[j + 1] = tmp;
        }
    }
}

console.log('arr', arr);//[ 1, 3, 5, 7, 9, 13, 2, 4, 10, 18 ]

at first I thought sort would create a new array, but not

.
let arr = [1, 2, 3, 4, 5, 7, 9, 10, 13, 18];

arr.sort((a, b) => {
    if (a % 2 === 0) {
        if (b % 2 !== 0) {
            return 1;
        }
        return 0;
    } else
        return -1
})

console.log('arr', arr);//[ 1, 3, 5, 7, 9, 13, 2, 4, 10, 18 ]

tested that sort is really fast, so it looks like you don't need to use native ones in the future. Array.prototype.sort sorting algorithm


[1, 2, 3, 4, 5] .sort (function (a, b) {/ does not include /})


arr.sort (a = > a% 2 = 0); but this kind of sorting is unstable because fast arrangement is used internally in sort, which is unstable.
merge or bubble these if you need stable sorting, and you can change the judgment conditions to

.
Menu