js面试题目:给定一个数组,有正数,负数和零,排列给定的数组,使负数在左边,0在中间,正数在右边

给定一个数组,有正数,负数和零,排列给定的数组,使负数在左边,0在中间,正数在右边。

let ar = [-1, 2, 0, -5, 0, 8, -4];

function swap(a, b) {
let c;
c = ar[a];
ar[a] = ar[b];
ar[b] = c;
}

function sortNumbers(len) {
let low = 0, mid = 0, high = len - 1;
while (mid <= high) {
if (ar[mid] < 0) {
swap(low++, mid++)
}
else if (ar[mid] == 0) {
mid++;
}
else
swap(mid, high--);
}
}
sortNumbers(ar.length)
console.log(ar)
posted @ 2020-03-07 14:13  逸_风  阅读(1473)  评论(0编辑  收藏  举报