MCPcopy Create free account
hub / github.com/ObEngine/ObEngine / auxsort

Function auxsort

extlibs/lua/src/ltablib.c:343–394  ·  view source on GitHub ↗

** Quicksort algorithm (recursive function) */

Source from the content-addressed store, hash-verified

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

Callers 1

sortFunction · 0.85

Calls 7

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

Tested by

no test coverage detected