首页 > 语言 > JavaScript > 正文

JavaScript实现快速排序的方法

2024-05-06 16:24:08
字体:大 中 小
来源:转载
供稿:网友

这篇文章主要介绍了JavaScript实现快速排序的方法,实例分析了javascript快速排序的相关实现技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了JavaScript实现快速排序的方法。分享给大家供大家参考。具体实现方法如下:

 

 
  1. <html> 
  2. <head> 
  3. <script> 
  4. function quickSort(input) { 
  5. if (input.length <= 1) return input; 
  6. var pivot = Math.floor(Math.random()*input.length) 
  7. var less = [], greater=[]; 
  8. var pivotElem = input.splice(pivot,1) 
  9. for (x in input) { 
  10. if (input[x] <= pivotElem[0]) 
  11. less.push(input[x]) 
  12. else 
  13. greater.push(input[x]) 
  14. } 
  15. return [].concat(quickSort(less),pivotElem,quickSort(greater)); 
  16. } 
  17. input = [] 
  18. inputSize = 1000 
  19. highestInputValue = 100 
  20. for (i=0;i<inputSize;i++) { 
  21. input.push(Math.floor(Math.random()*highestInputValue)) 
  22. } 
  23. document.writeln(quickSort(input)) 
  24. </script> 
  25. </head> 
  26. </body> 
  27. </html> 

希望本文所述对大家的javascript程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选