这是 JS 中不同排序算法的列表。我制作了一个比较排序时间的页面,并且我注意到“快速”似乎是最好的选择。
冒泡排序:
var arrBubble= new Array();
var tmpBubble;
function srtBubble(){
tmpDate=new Date();
timBegin=tmpDate.getTime();
var blnBubbleSwitch;
do {
blnBubbleSwitch=false;
for(var i=0;i<arrBubble.length-1;i++){
if(arrBubble[i]>arrBubble[i+1])
{
tmpBubble=arrBubble[i];
arrBubble[i]=arrBubble[i+1];
arrBubble[i+1]=tmpBubble;
blnBubbleSwitch=true;
}
}
} while(blnBubbleSwitch);
}
插入:
var arrinsertion= new Array();
var tmpinsertion;
function srtinsertionion(){
var j;
blninsertionSwitch=false;
for(var i=0;i<arrinsertion.length;i++){
tmpinsertion=arrinsertion[i];
j=i;
while((j>=0)&&arrinsertion[j-1]>tmpinsertion)
{
arrinsertion[j]=arrinsertion[j-1];
j--;
//blninsertionSwitch=true;
}
arrinsertion[j]=tmpinsertion;
}
}
壳:
function srtShell(){
var arrShell= new Array();
for (var h = arrShell.length; h = parseInt(h / 2);) {
for (var i = h; i < arrShell.length; i++) {
var k = arrShell[i];
for (var j = i; j >= h && k < arrShell[j - h]; j -= h)
arrShell[j] = arrShell[j - h];
arrShell[j] = k;
}
}
}
快的:
function srtQuick()
{
var arrQuick= new Array();
qsort(arrQuick, 0, arrQuick.length);
}
function qsort(array, begin, end)
{
if(end-1>begin) {
var pivot=begin+Math.floor(Math.random()*(end-begin));
pivot=partition(array, begin, end, pivot);
qsort(array, begin, pivot);
qsort(array, pivot+1, end);
}
}
Array.prototype.swap=function(a, b)
{
var tmp=this[a];
this[a]=this[b];
this[b]=tmp;
}
function partition(array, begin, end, pivot)
{
var piv=array[pivot];
array.swap(pivot, end-1);
var store=begin;
var ix;
for(ix=begin; ix<end-1; ++ix) {
if(array[ix]<=piv) {
array.swap(store, ix);
++store;
}
}
array.swap(end-1, store);
return store;
}
合并:
function merge_inplace(array, begin, begin_right, end)
{
var arrMerge= new Array();
for(;begin<begin_right; ++begin) {
if(array[begin]>array[begin_right]) {
var v=array[begin];
array[begin]=array[begin_right];
insertion(array, begin_right, end, v);
}
}
}
function insertion(array, begin, end, v)
{
while(begin+1<end && array[begin+1]<v) {
array.swap(begin, begin+1);
++begin;
}
array[begin]=v;
}
function msort(array, begin, end)
{
var size=end-begin;
if(size<2) return;
var begin_right=begin+Math.floor(size/2);
msort(array, begin, begin_right);
msort(array, begin_right, end);
merge_inplace(array, begin, begin_right, end);
}
function srtMerge()
{
msort(arrMerge, 0, arrMerge.length);
}
内置JS排序:
function srtJSSort()
{
var arrJSSort= new Array();
arrJSSort.sort(function(a,b){return a-b});
}
当然我会建议在函数之外使用你的数组,这样你就可以在数据排序后继续使用它。