MCPcopy Create free account
hub / github.com/DFHack/dfhack / auxsort

Function auxsort

depends/lua/src/ltablib.c:357–408  ·  view source on GitHub ↗

** QuickSort algorithm (recursive function) */

Source from the content-addressed store, hash-verified

355** QuickSort algorithm (recursive function)
356*/
357static void auxsort (lua_State *L, IdxT lo, IdxT up,
358 unsigned int rnd) {
359 while (lo < up) { /* loop for tail recursion */
360 IdxT p; /* Pivot index */
361 IdxT n; /* to be used later */
362 /* sort elements 'lo', 'p', and 'up' */
363 lua_geti(L, 1, lo);
364 lua_geti(L, 1, up);
365 if (sort_comp(L, -1, -2)) /* a[up] < a[lo]? */
366 set2(L, lo, up); /* swap a[lo] - a[up] */
367 else
368 lua_pop(L, 2); /* remove both values */
369 if (up - lo == 1) /* only 2 elements? */
370 return; /* already sorted */
371 if (up - lo < RANLIMIT || rnd == 0) /* small interval or no randomize? */
372 p = (lo + up)/2; /* middle element is a good pivot */
373 else /* for larger intervals, it is worth a random pivot */
374 p = choosePivot(lo, up, rnd);
375 lua_geti(L, 1, p);
376 lua_geti(L, 1, lo);
377 if (sort_comp(L, -2, -1)) /* a[p] < a[lo]? */
378 set2(L, p, lo); /* swap a[p] - a[lo] */
379 else {
380 lua_pop(L, 1); /* remove a[lo] */
381 lua_geti(L, 1, up);
382 if (sort_comp(L, -1, -2)) /* a[up] < a[p]? */
383 set2(L, p, up); /* swap a[up] - a[p] */
384 else
385 lua_pop(L, 2);
386 }
387 if (up - lo == 2) /* only 3 elements? */
388 return; /* already sorted */
389 lua_geti(L, 1, p); /* get middle element (Pivot) */
390 lua_pushvalue(L, -1); /* push Pivot */
391 lua_geti(L, 1, up - 1); /* push a[up - 1] */
392 set2(L, p, up - 1); /* swap Pivot (a[p]) with a[up - 1] */
393 p = partition(L, lo, up);
394 /* a[lo .. p - 1] <= a[p] == P <= a[p + 1 .. up] */
395 if (p - lo < up - p) { /* lower interval is smaller? */
396 auxsort(L, lo, p - 1, rnd); /* call recursively for lower interval */
397 n = p - lo; /* size of smaller interval */
398 lo = p + 1; /* tail call for [p + 1 .. up] (upper interval) */
399 }
400 else {
401 auxsort(L, p + 1, up, rnd); /* call recursively for upper interval */
402 n = up - p; /* size of smaller interval */
403 up = p - 1; /* tail call for [lo .. p - 1] (lower interval) */
404 }
405 if ((up - lo) / 128 > n) /* partition too imbalanced? */
406 rnd = l_randomizePivot(); /* try a new randomization */
407 } /* tail call auxsort(L, lo, up, rnd) */
408}
409
410
411static int sort (lua_State *L) {

Callers 1

sortFunction · 0.85

Calls 7

lua_getiFunction · 0.85
sort_compFunction · 0.85
set2Function · 0.85
choosePivotFunction · 0.85
lua_pushvalueFunction · 0.85
partitionFunction · 0.85
l_randomizePivotFunction · 0.85

Tested by

no test coverage detected