How to implement quick sort in JavaScript?

Object Oriented ProgrammingJavascriptProgramming

Quick sort

Quick sort is one of the most important sorting methods in javascript. It takes a pivot value(a random value) from an array. All the other elements in the array are split to two categories.They may be less than the pivot value and greater than the pivot value.

After that each of the categories(less than the pivot and greater than the pivot) are subjected to the same procedure that is a pivot is chosen then each category is divided in to sub-categories(less than the pivot and greater than the pivot).

Eventually, the sub-categories are divided in such a way that they may contain an element or no element if there are no more elements to compare. The rest of the values will be denoted as a pivots at some previous points and did not trickle down to this lowest sub category.

Example

Live Demo

<html>
<body>
<script>
   function quickSort(originalArr) {
      if (originalArr.length <= 1) {
         return originalArr;
         } else {
               var leftArr = [];              
               var rightArr = [];
               var newArr = [];
               var pivot = originalArr.pop();      //  Take a pivot value
               var length = originalArr.length;
               for (var i = 0; i < length; i++) {
                  if (originalArr[i] <= pivot) {    // using pivot value start comparing
                     leftArr.push(originalArr[i]);      
               } else {
                       rightArr.push(originalArr[i]);
             }
           }
         return newArr.concat(quickSort(leftArr), pivot, quickSort(rightArr)); // array will be                                                                            //returned untill sorting occurs
      }
   }
   var myArray = [9, 0, 2, 7, -2, 6, 1 ];
   document.write("Original array: " + myArray);
   var sortedArray = quickSort(myArray);
   document.write("Sorted array: " + sortedArray);
</script>
</body>
</html>

output

Original array: 9,0,2,7,-2,6,1
Sorted array: -2,0,1,2,6,7,9
raja
Published on 04-Jun-2019 11:48:52
Advertisements