<script> //用来调用排列方法的类 function arr_sort(arr){ var startTime,endTime; var priv_arr = new Array; for(var key in arr){ priv_arr.push(arr[key]); } this.get_arr = function(){ return priv_arr } //快速排序 this.sort1 = function(){ startTime = new Date().getTime(); quickSort(0,priv_arr.length-1); endTime = new Date().getTime(); } function swap(l,r){ var temp = priv_arr[l]; priv_arr[l] = priv_arr[r]; priv_arr[r] = temp; } function quickSort(left,right){ if(left<right){ var i=left-1; var last = priv_arr[right]; var j = right; while(true){ while(priv_arr[++i] < last); while(j>0){ if(priv_arr[--j] <= last)break; } if(i>=j)break; swap(i,j) } swap(i,right); quickSort(left,i-1); quickSort(i+1,right); } } //合并排序 this.sort2 = function(){ startTime = getCurrTime(); merge_split(priv_arr,0,priv_arr.length-1); endTime = getCurrTime(); } function merge_split(arr,left,right){ if(left >= right){ return; } var middle=(left+right)>>>1; //document.write(left+"\t"+middle+"\t"+right+"<br>"); merge_split(arr,left,middle); merge_split(arr,middle+1,right); merge(arr,left,right,middle); } function merge(arr,l,r,m){ var i =l; var j =m+1; //document.write(l+"\t"+m+"\t"+r+"<br>"); while(i<j&&j<=r){ //document.write("$$"+i+"\t"+"\t"+j+"<br>"); if(arr[i]>arr[j]){ var t = arr[j]; for(var k=j;k>i;k--){ arr[k]=arr[k-1]; } arr[i]=t; //document.write("####"+priv_arr.toString()+"<br>"); j++; } i++; } //document.write(priv_arr.toString()+"<br>"); } function getCurrTime(){ return new Date().getTime(); } this.getExTime = function(){ document.write(startTime+" "+endTime+"<br>"); return endTime - startTime; } } //用来生成随即数组的函数 function random_array(size){ var arr = new Array; for(var i=0;i<size;i++){ arr.push(parseInt(Math.random()*100)); } return arr; } var arr_test = random_array(3000); document.write(arr_test.toString()+"<br>"); var sort1 = new arr_sort(arr_test); var sort2 = new arr_sort(arr_test); var dur_time; sort1.sort1(); var my_arr1 = sort1.get_arr(); sort2.sort2(); var my_arr2 = sort2.get_arr(); document.write("quick_sort:<br>"); document.write(my_arr1.toString()+"<br>"); document.write("Time:"+sort1.getExTime()+"<br>"); document.write("merge_sort:<br>"); document.write(my_arr2.toString()+"<br>"); document.write("Time:"+sort2.getExTime()+"<br>"); document.write(arr_test.toString()+"<br>"); </script >