MCPcopy Create free account
hub / github.com/RomanKubiak/ctrlr / auxsort

Function auxsort

Source/Misc/lua/src/lua.c:14739–14800  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

14737}
14738
14739static void auxsort (lua_State *L, int l, int u) {
14740while (l < u) { /* for tail recursion */
14741int i, j;
14742/* sort elements a[l], a[(l+u)/2] and a[u] */
14743lua_rawgeti(L, 1, l);
14744lua_rawgeti(L, 1, u);
14745if (sort_comp(L, -1, -2)) /* a[u] < a[l]? */
14746set2(L, l, u); /* swap a[l] - a[u] */
14747else
14748lua_pop(L, 2);
14749if (u-l == 1) break; /* only 2 elements */
14750i = (l+u)/2;
14751lua_rawgeti(L, 1, i);
14752lua_rawgeti(L, 1, l);
14753if (sort_comp(L, -2, -1)) /* a[i]<a[l]? */
14754set2(L, i, l);
14755else {
14756lua_pop(L, 1); /* remove a[l] */
14757lua_rawgeti(L, 1, u);
14758if (sort_comp(L, -1, -2)) /* a[u]<a[i]? */
14759set2(L, i, u);
14760else
14761lua_pop(L, 2);
14762}
14763if (u-l == 2) break; /* only 3 elements */
14764lua_rawgeti(L, 1, i); /* Pivot */
14765lua_pushvalue(L, -1);
14766lua_rawgeti(L, 1, u-1);
14767set2(L, i, u-1);
14768/* a[l] <= P == a[u-1] <= a[u], only need to sort from l+1 to u-2 */
14769i = l; j = u-1;
14770for (;;) { /* invariant: a[l..i] <= P <= a[j..u] */
14771/* repeat ++i until a[i] >= P */
14772while (lua_rawgeti(L, 1, ++i), sort_comp(L, -1, -2)) {
14773if (i>u) luaL_error(L, "invalid order function for sorting");
14774lua_pop(L, 1); /* remove a[i] */
14775}
14776/* repeat --j until a[j] <= P */
14777while (lua_rawgeti(L, 1, --j), sort_comp(L, -3, -1)) {
14778if (j<l) luaL_error(L, "invalid order function for sorting");
14779lua_pop(L, 1); /* remove a[j] */
14780}
14781if (j<i) {
14782lua_pop(L, 3); /* pop pivot, a[i], a[j] */
14783break;
14784}
14785set2(L, i, j);
14786}
14787lua_rawgeti(L, 1, u-1);
14788lua_rawgeti(L, 1, i);
14789set2(L, u-1, i); /* swap pivot (a[u-1]) with a[i] */
14790/* a[l..i-1] <= a[i] == P <= a[i+1..u] */
14791/* adjust so that smaller half is in [j..i] and larger one in [l..u] */
14792if (i-l < u-i) {
14793j=l; i=i-1; l=i+2;
14794}
14795else {
14796j=i+1; i=u; u=j-2;

Callers 1

sortFunction · 0.85

Calls 5

lua_rawgetiFunction · 0.85
sort_compFunction · 0.85
set2Function · 0.85
lua_pushvalueFunction · 0.85
luaL_errorFunction · 0.85

Tested by

no test coverage detected