** Does the partition: Pivot P is at the top of the stack. ** precondition: a[lo] <= P == a[up-1] <= a[up], ** so it only needs to do the partition from lo + 1 to up - 2. ** Pos-condition: a[lo .. i - 1] <= a[i] == P <= a[i + 1 .. up] ** returns 'i'. */
| 308 | ** returns 'i'. |
| 309 | */ |
| 310 | static IdxT partition (lua_State *L, IdxT lo, IdxT up) { |
| 311 | IdxT i = lo; /* will be incremented before first use */ |
| 312 | IdxT j = up - 1; /* will be decremented before first use */ |
| 313 | /* loop invariant: a[lo .. i] <= P <= a[j .. up] */ |
| 314 | for (;;) { |
| 315 | /* next loop: repeat ++i while a[i] < P */ |
| 316 | while (lua_geti(L, 1, ++i), sort_comp(L, -1, -2)) { |
| 317 | if (i == up - 1) /* a[i] < P but a[up - 1] == P ?? */ |
| 318 | luaL_error(L, "invalid order function for sorting"); |
| 319 | lua_pop(L, 1); /* remove a[i] */ |
| 320 | } |
| 321 | /* after the loop, a[i] >= P and a[lo .. i - 1] < P */ |
| 322 | /* next loop: repeat --j while P < a[j] */ |
| 323 | while (lua_geti(L, 1, --j), sort_comp(L, -3, -1)) { |
| 324 | if (j < i) /* j < i but a[j] > P ?? */ |
| 325 | luaL_error(L, "invalid order function for sorting"); |
| 326 | lua_pop(L, 1); /* remove a[j] */ |
| 327 | } |
| 328 | /* after the loop, a[j] <= P and a[j + 1 .. up] >= P */ |
| 329 | if (j < i) { /* no elements out of place? */ |
| 330 | /* a[lo .. i - 1] <= P <= a[j + 1 .. i .. up] */ |
| 331 | lua_pop(L, 1); /* pop a[j] */ |
| 332 | /* swap pivot (a[up - 1]) with a[i] to satisfy pos-condition */ |
| 333 | set2(L, up - 1, i); |
| 334 | return i; |
| 335 | } |
| 336 | /* otherwise, swap a[i] - a[j] to restore invariant and repeat */ |
| 337 | set2(L, i, j); |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | |
| 342 | /* |
no test coverage detected