手动实现sort排序函数——javascript底层逻辑研究

zhuanbike 2022-2-27 712

使用sort函数,function(a,b){return a-b)这样的方式可以实现数组的从小到大排序,那么这个sort方法的底层原理是什么呢,这里手动实现一下,作为一个了解吧,实际项目当中,我们使用sort方法就够用了,但是底层逻辑还是需要理解的。

			let arr4 = [11, 1, 3, 5, 7, 9];
			function sorttest(arrtest,callback) {
				for (const n in arrtest) {
					for (const m in arrtest) {
						if (callback(arrtest[n],arrtest[m])<0) {
							const temp = arrtest[n]; //arrtest[1]=11,arrtest[2]=1举例 temp=11遇到了1
							arrtest[n] = arrtest[m]; //arrtest[1]就等于1
							arrtest[m] = temp; //arrtest[2]就等于了11 就完成了大小换位
						}
					}
				}
				return arrtest;
			};
			arr4=sorttest(arr4,function(a, b) {
				return a - b;
			});
			console.log(arr4);


最新回复 (0)
发新帖