MCPcopy Create free account
hub / github.com/Serial-Studio/Serial-Studio / auxsort

Function auxsort

lib/lua/src/ltablib.c:345–396  ·  view source on GitHub ↗

** Quicksort algorithm (recursive function) */

Source from the content-addressed store, hash-verified

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