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