Quick Sort is my favorite sort algorithm. The reason is simple: Quick Sort is efficient enough and easy to understand and implement, in recursive way or not.
Like Merge Sort, we applies sub-grouping concept here as well. The difference is that we select a pivot randomly in the sorting array first, then put all the elements smaller or equal to a left sub group and put rest of elements to a right group. The pivot will be in the middle right between two sub groups. Very easy, right? Finding a element as a pivot, smaller ones go left and bigger ones go right. Now, we have two small groups, each group repeats the process again, until only zero or one element in a sub group. If you are using recursive method, this is the condition for your method to exit the loop and return.
During the animation show for Quick Sort below, I select first element of a group as pivot and mark pivots as black rectangle after I sub-group rest elements. Different sub-group will be filled with different colour in their rectangle. The animation will make sense to you once you understand Quick Sort algorithm I mentioned above.
Like Merge Sort, we applies sub-grouping concept here as well. The difference is that we select a pivot randomly in the sorting array first, then put all the elements smaller or equal to a left sub group and put rest of elements to a right group. The pivot will be in the middle right between two sub groups. Very easy, right? Finding a element as a pivot, smaller ones go left and bigger ones go right. Now, we have two small groups, each group repeats the process again, until only zero or one element in a sub group. If you are using recursive method, this is the condition for your method to exit the loop and return.
During the animation show for Quick Sort below, I select first element of a group as pivot and mark pivots as black rectangle after I sub-group rest elements. Different sub-group will be filled with different colour in their rectangle. The animation will make sense to you once you understand Quick Sort algorithm I mentioned above.
$scope.quickSort = function(list){ if(list.length <= 1){ return list; } var left = []; var right = []; var pivot = list[0]; for(var i = 1; i < list.length; i++){ if(list[i] <= pivot){ left.push(list[i]); }else{ right.push(list[i]); } } return $scope.quickSort(left).concat(pivot).concat($scope.quickSort(right)); }
Of course, you still can implement Quick Sort in a non-recursive way. How, I hope you can figure it out by yourself. Hint: instead of depending on JavaScript engine put your env into a stack, you can have your own stack to push and pop sub group information for future usage. Anyway, if you want to see the answer directly, press F12, all the sort animation source codes are available in current web page. Yes, I have to show the Quick Sort animation in a non-recursive way. Don't be scared by AngularJS and D3 related codes, just focus on quickSortShow() function.