JavaScript快速排序

编程入门 行业动态 更新时间:2024-10-09 11:18:45
本文介绍了JavaScript快速排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直在网上浏览一段时间,我想知道是否存在通常使用的快速排序的'稳定'的事实实现?我可以写自己的,但为什么重新发明轮子...

I have been looking around the web for a while and I am wondering if there is a 'stable' defacto implementation of quicksort that is generally used? I can write my own but why reinvent the wheel...

推荐答案

你可以使用装饰轻松稳定不稳定的排序-sort-undecorate模式

You can easily "stabilize" an unstable sort using a decorate-sort-undecorate pattern

function stableSort(v, f) { if (f === undefined) { f = function(a, b) { a = ""+a; b = ""+b; return a < b ? -1 : (a > b ? 1 : 0); } } var dv = []; for (var i=0; i<v.length; i++) { dv[i] = [v[i], i]; } dv.sort(function(a, b){ return f(a[0], b[0]) || (a[1] - b[1]); }); for (var i=0; i<v.length; i++) { v[i] = dv[i][0]; } }

想法是将索引添加为最后一个排序术语所以没有两个元素现在相同,如果其他一切都相同,原始索引将成为区别因素。

the idea is to add the index as last sorting term so that no two elements are now "the same" and if everything else is the same the original index will be the discriminating factor.

更多推荐

JavaScript快速排序

本文发布于:2023-11-29 06:49:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645650.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:快速   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!