Javascript quicksort algorithm

  • 2020-03-30 03:58:03
  • OfStack

The idea of quicksort is simple. The whole process takes three steps:

(1) find a reference point in the data set

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

(3) use recursion for the next comparison

To see a demo: (link: http://jsdo.it/norahiko/oxIy/fullscreen) (web page may be slower, slowly waiting for?)


<script type="text/javascript"> 

function quickSort(arr){
  if(arr.length<=1){
    return arr;//If the array has only one number, it simply returns;
  }

  var num = Math.floor(arr.length/2);//Find the index value of the middle number, and if it is a floating point number, round down
  var numValue = arr.splice(num,1);//Find the middle number
  var left = [];
  var right = [];

  for(var i=0;i<arr.length;i++){
    if(arr[i]<numValue){
      left.push(arr[i]);//The data to the left of the reference point is passed to the left array
    }
    else{
      right.push(arr[i]);//The number to the right of the reference point is passed to the array to the right
    }
  }
 return quickSort(left).concat([numValue],quickSort(right));//The recursion repeats the comparison
}
alert(quickSort([32,45,37,16,2,87]));//The pop-up "2,16,32,37,45,87"

</script>


Related articles: