@@ -33,61 +33,3 @@ function quicksortBasic(array) {
3333
3434console . log ( quicksortBasic ( array . slice ( ) ) ) ; // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
3535
36- // swap function helper
37- function swap ( array , i , j ) {
38- var temp = array [ i ] ;
39- array [ i ] = array [ j ] ;
40- array [ j ] = temp ;
41- }
42-
43- // classic implementation (with Hoare or Lomuto partition scheme, you can comment either one method or the other to see the difference)
44- function quicksort ( array , left , right ) {
45- left = left || 0 ;
46- right = right || array . length - 1 ;
47-
48- // var pivot = partitionLomuto(array, left, right); // you can play with both partition
49- var pivot = partitionHoare ( array , left , right ) ; // you can play with both partition
50-
51- if ( left < pivot - 1 ) {
52- quicksort ( array , left , pivot - 1 ) ;
53- }
54- if ( right > pivot ) {
55- quicksort ( array , pivot , right ) ;
56- }
57- return array ;
58- }
59- // Lomuto partition scheme, it is less efficient than the Hoare partition scheme
60- function partitionLomuto ( array , left , right ) {
61- var pivot = right ;
62- var i = left ;
63-
64- for ( var j = left ; j < right ; j ++ ) {
65- if ( array [ j ] <= array [ pivot ] ) {
66- swap ( array , i , j ) ;
67- i = i + 1 ;
68- }
69- }
70- swap ( array , i , j ) ;
71- return i ;
72- }
73- // Hoare partition scheme, it is more efficient than the Lomuto partition scheme because it does three times fewer swaps on average
74- function partitionHoare ( array , left , right ) {
75- var pivot = Math . floor ( ( left + right ) / 2 ) ;
76-
77- while ( left <= right ) {
78- while ( array [ left ] < array [ pivot ] ) {
79- left ++ ;
80- }
81- while ( array [ right ] > array [ pivot ] ) {
82- right -- ;
83- }
84- if ( left <= right ) {
85- swap ( array , left , right ) ;
86- left ++ ;
87- right -- ;
88- }
89- }
90- return left ;
91- }
92-
93- console . log ( quicksort ( array . slice ( ) ) ) ; // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
0 commit comments