Home  >  Article  >  Web Front-end  >  Detailed explanation of javascript quick sort algorithm_javascript skills

Detailed explanation of javascript quick sort algorithm_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:36:101581browse

The idea of ​​"quick sort" is very simple. The entire sorting process only requires three steps:

(1) Find a reference point in the data set

(2) Create two arrays to store the left and right arrays respectively

(3) Use recursion for the next comparison

Watch a demo: http://jsdo.it/norahiko/oxIy/fullscreen (The webpage may be slow to open, please wait)

<script type="text/javascript"> 

function quickSort(arr){
  if(arr.length<=1){
    return arr;//如果数组只有一个数,就直接返回;
  }

  var num = Math.floor(arr.length/2);//找到中间数的索引值,如果是浮点数,则向下取整
  var numValue = arr.splice(num,1);//找到中间数的值
  var left = [];
  var right = [];

  for(var i=0;i<arr.length;i++){
    if(arr[i]<numValue){
      left.push(arr[i]);//基准点的左边的数传到左边数组
    }
    else{
      right.push(arr[i]);//基准点的右边的数传到右边数组
    }
  }
 return quickSort(left).concat([numValue],quickSort(right));//递归不断重复比较
}
alert(quickSort([32,45,37,16,2,87]));//弹出“2,16,32,37,45,87”

</script>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn