一个js面试题

事情是这样的,作为一个应届生小菜,前些天去人人网面试了
面试官给出了一个题:js实现:一个数组,把奇数放到右边,偶数放到左边,不许使用额外空间。

于是我开始思考,其实如果能使用额外空间的话,额外申请一个数组,根本不是问题。
也想过类似于排序的交换方法,可是交换也需要额外的临时变量tmp不是咩?
而且js好像也没有类似于C语言swap的方法啊

于是我这样:

https://img3.mukewang.com/5b65b57f0001255a03060193.jpg

但是面试官边玩手机边用余光瞥了一眼,继续玩手机,然后又瞥了一眼,终于开口说:你知道从数组中间删除一个元素,splice的运行代价有多大吗?

所以该怎么做呢?


慕桂英546537
浏览 1073回答 3
3回答

慕慕森

Array.prototype.swap = function(a, b) {&nbsp; &nbsp; this[a] ^= this[b];&nbsp; &nbsp; this[b] ^= this[a];&nbsp; &nbsp; this[a] ^= this[b];}Array.prototype.OddSort = function() {&nbsp; &nbsp; for (var i = this.length - 1; i > 0; --i) {&nbsp; &nbsp; &nbsp; &nbsp; for (var j = 0; j < i; ++j)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (this[j] & 1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.swap(j, j + 1);&nbsp; &nbsp; }}var arr = [2, 4, 77, 788, 2, 0, 99, 10];arr.OddSort();console.log(arr)

人到中年有点甜

一句话arr.sort(function(a,b){return a%2!==0})
打开App,查看更多内容
随时随地看视频慕课网APP