Skip to content

Commit f94e574

Browse files
committed
3 ways quick sort
1 parent bdde4a9 commit f94e574

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

src/jssort.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,40 @@ var jssort = jssort || {};
183183
jss.exchange(a, lo, j);
184184
return j;
185185
};
186+
187+
jss.threeWaysQuickSort = function (a, lo, hi, compare) {
188+
if (!lo) lo = 0;
189+
if (!hi) hi = a.length-1;
190+
if (!compare) {
191+
compare = function (a1, a2){
192+
return a1 - a2;
193+
};
194+
}
195+
196+
if (lo >= hi) {
197+
return;
198+
}
199+
200+
if (hi - lo <= 7) {
201+
jss.insertionSort(a, lo, hi, compare);
202+
return;
203+
}
204+
205+
var i = lo, lt = lo, gt = hi;
206+
var v = a[lo];
207+
while (i < gt) {
208+
if (jss.less(a[i], v, compare)) {
209+
jss.exchange(a, i++, lt++);
210+
} else if(jss.less(v, a[i], compare)) {
211+
jss.exchange(a, i, gt--);
212+
} else {
213+
i++;
214+
}
215+
}
216+
217+
jss.threeWaysQuickSort(a, lo, lt-1, compare);
218+
jss.threeWaysQuickSort(a, gt+1, hi, compare);
219+
};
186220

187221
})(jssort);
188222

0 commit comments

Comments
 (0)