当前位置:Gxlcms > JavaScript > JavaScript实现快速排序的方法

JavaScript实现快速排序的方法

时间:2021-07-01 10:21:17 帮助过:24人阅读

本文实例讲述了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程序设计有所帮助。

人气教程排行