September 2017 Update

This commit is contained in:
Ingy döt Net 2017-09-23 10:01:46 +02:00
parent bba7bfd280
commit ba8067c3b7
14570 changed files with 153136 additions and 63871 deletions

View file

@ -1,23 +1,31 @@
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <time.h>
typedef unsigned uint;
#define swap(a, b) { tmp = a; a = b; b = tmp; }
#define each(i, x) for (i = 0; i < x; i++)
// Get size of statically allocated array
#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR)
// Generate random number in the interval [M,N]
#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1));
static void swap(unsigned *a, unsigned *b) {
unsigned tmp = *a;
*a = *b;
*b = tmp;
}
/* sort unsigned ints */
static void rad_sort_u(uint *from, uint *to, uint bit)
static void rad_sort_u(unsigned *from, unsigned *to, unsigned bit)
{
if (!bit || to < from + 1) return;
uint *ll = from, *rr = to - 1, tmp;
while (1) {
unsigned *ll = from, *rr = to - 1;
for (;;) {
/* find left most with bit, and right most without bit, swap */
while (ll < rr && !(*ll & bit)) ll++;
while (ll < rr && (*rr & bit)) rr--;
if (ll >= rr) break;
swap(*ll, *rr);
swap(ll, rr);
}
if (!(bit & *ll) && ll < to) ll++;
@ -31,27 +39,28 @@ static void rad_sort_u(uint *from, uint *to, uint bit)
static void radix_sort(int *a, const size_t len)
{
size_t i;
uint *x = (uint*) a;
unsigned *x = (unsigned*) a;
each(i, len) x[i] ^= INT_MIN;
rad_sort_u(x, x + len, INT_MIN);
each(i, len) x[i] ^= INT_MIN;
}
for (i = 0; i < len; i++)
x[i] ^= INT_MIN;
static inline void radix_sort_unsigned(uint *a, const size_t len)
{
rad_sort_u(a, a + len, (uint)INT_MIN);
rad_sort_u(x, x + len, INT_MIN);
for (i = 0; i < len; i++)
x[i] ^= INT_MIN;
}
int main(void)
{
int len = 16, x[16], i;
size_t len = 16, i;
each(i, len) x[i] = rand() % 512 - 256;
radix_sort(x, len);
srand(time(NULL));
int x[16];
each(i, len) printf("%d%c", x[i], i + 1 < len ? ' ' : '\n');
for (size_t i = 0; i < ARR_LEN(x); i++)
x[i] = RAND_RNG(-128,127)
return 0;
radix_sort(x, ARR_LEN(x));
for (size_t i = 0; i < ARR_LEN(x); i++)
printf("%d%c", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\n');
}

View file

@ -0,0 +1,168 @@
*=======================================================================
* RSORT - sort a list of integers by the Radix Sort algorithm
* Public domain. This program may be used by any person for any purpose.
* Origin: Herman Hollerith, 1887
*
*___Name____Type______In/Out____Description_____________________________
* IX(N) Integer Both Array to be sorted in increasing order
* IW(N) Integer Neither Workspace
* N Integer In Length of array
*
* ASSUMPTIONS: Bits in an INTEGER is an even number.
* Integers are represented by twos complement.
*
* NOTE THAT: Radix sorting has an advantage when the input is known
* to be less than some value, so that only a few bits need
* to be compared. This routine looks at all the bits,
* and is thus slower than Quicksort.
*=======================================================================
SUBROUTINE RSORT (IX, IW, N)
IMPLICIT NONE
INTEGER IX, IW, N
DIMENSION IX(N), IW(N)
INTEGER I, ! count bits
$ ILIM, ! bits in an integer
$ J, ! count array elements
$ P1OLD, P0OLD, P1, P0, ! indices to ones and zeros
$ SWAP
LOGICAL ODD ! even or odd bit position
* IF (N < 2) RETURN ! validate
J = 0 ! find bit size of an integer
J = NOT(J)
ILIM = 0
DO I = 1, 32767 ! much bigger than exists
J = ISHFT(J, -1)
IF (.NOT. BTEST(J, 0)) THEN
ILIM = I
GO TO 10
END IF
END DO
10 CONTINUE
*=======================================================================
* Alternate between putting data into IW and into IX
*=======================================================================
P1 = N+1
P0 = N ! read from 1, N on first pass thru
ODD = .FALSE.
DO I = 0, ILIM-2
P1OLD = P1
P0OLD = P0 ! save the value from previous bit
P1 = N+1
P0 = 0 ! start a fresh count for next bit
IF (ODD) THEN
DO J = 1, P0OLD, +1 ! copy data from the zeros
IF ( BTEST(IW(J), I) ) THEN
P1 = P1 - 1
IX(P1) = IW(J)
ELSE
P0 = P0 + 1
IX(P0) = IW(J)
END IF
END DO
DO J = N, P1OLD, -1 ! copy data from the ones
IF ( BTEST(IW(J), I) ) THEN
P1 = P1 - 1
IX(P1) = IW(J)
ELSE
P0 = P0 + 1
IX(P0) = IW(J)
END IF
END DO
ELSE
DO J = 1, P0OLD, +1 ! copy data from the zeros
IF ( BTEST(IX(J), I) ) THEN
P1 = P1 - 1
IW(P1) = IX(J)
ELSE
P0 = P0 + 1
IW(P0) = IX(J)
END IF
END DO
DO J = N, P1OLD, -1 ! copy data from the ones
IF ( BTEST(IX(J), I) ) THEN
P1 = P1 - 1
IW(P1) = IX(J)
ELSE
P0 = P0 + 1
IW(P0) = IX(J)
END IF
END DO
END IF ! even or odd i
ODD = .NOT. ODD
END DO ! next i
*=======================================================================
* the sign bit
*=======================================================================
P1OLD = P1
P0OLD = P0
P1 = N+1
P0 = 0
* if sign bit is set, send to the zero end
DO J = 1, P0OLD, +1
IF ( BTEST(IW(J), ILIM-1) ) THEN
P0 = P0 + 1
IX(P0) = IW(J)
ELSE
P1 = P1 - 1
IX(P1) = IW(J)
END IF
END DO
DO J = N, P1OLD, -1
IF ( BTEST(IW(J), ILIM-1) ) THEN
P0 = P0 + 1
IX(P0) = IW(J)
ELSE
P1 = P1 - 1
IX(P1) = IW(J)
END IF
END DO
*=======================================================================
* Reverse the order of the greater value partition
*=======================================================================
P1OLD = P1
DO J = N, (P1OLD+N)/2+1, -1
SWAP = IX(J)
IX(J) = IX(P1)
IX(P1) = SWAP
P1 = P1 + 1
END DO
RETURN
END ! of RSORT
***********************************************************************
* test program
***********************************************************************
PROGRAM t_sort
IMPLICIT NONE
INTEGER I, N
PARAMETER (N = 11)
INTEGER IX(N), IW(N)
LOGICAL OK
DATA IX / 2, 24, 45, 0, 66, 75, 170, -802, -90, 1066, 666 /
PRINT *, 'before: ', IX
CALL RSORT (IX, IW, N)
PRINT *, 'after: ', IX
* compare
OK = .TRUE.
DO I = 1, N-1
IF (IX(I) > IX(I+1)) OK = .FALSE.
END DO
IF (OK) THEN
PRINT *, 't_sort: successful test'
ELSE
PRINT *, 't_sort: failure!'
END IF
END ! of test program

View file

@ -0,0 +1,36 @@
// version 1.1.2
fun radixSort(original: IntArray): IntArray {
var old = original // Need this to be mutable
// Loop for every bit in the integers
for (shift in 31 downTo 0) {
val tmp = IntArray(old.size) // The array to put the partially sorted array into
var j = 0 // The number of 0s
// Move the 0s to the new array, and the 1s to the old one
for (i in 0 until old.size) {
// If there is a 1 in the bit we are testing, the number will be negative
val move = (old[i] shl shift) >= 0
// If this is the last bit, negative numbers are actually lower
val toBeMoved = if (shift == 0) !move else move
if (toBeMoved)
tmp[j++] = old[i]
else {
// It's a 1, so stick it in the old array for now
old[i - j] = old[i]
}
}
// Copy over the 1s from the old array
for (i in j until tmp.size) tmp[i] = old[i - j]
// And now the tmp array gets switched for another round of sorting
old = tmp
}
return old
}
fun main(args: Array<String>) {
val arrays = arrayOf(
intArrayOf(170, 45, 75, -90, -802, 24, 2, 66),
intArrayOf(-4, 5, -26, 58, -990, 331, 331, 990, -1837, 2028)
)
for (array in arrays) println(radixSort(array).contentToString())
}

View file

@ -1,63 +1,62 @@
/*REXX program performs a radix sort on an integer (can be neg/zero/pos) array*/
ILF='0 2 3 4 5 5 7 6 6 7 11 7 13 9 8 8 17 8 19 9 10 13 23 9 10 15 9 11 29 10 31 10 14 19',
'12 10 37 21 16 11 41 12 43 15 11 25 47 11 14 12 20 17 53 11 16 13 22 31 59 12 61 33',
'13 12 18 16 67 21 26 14 71 12 73 39 13 23 18 18 79 13 12 43 83 14 22 45 32 17 89 13',
'20 27 34 49 24 13 97 16 17 14 101 22 103 19 15 55 107 13 109 18 40 15 113 -42'
/*excluding -42, the abbreviated list (above) is called the integer log function.*/
n=words(ILF) /* I────── L── F─────── */
w=0 /*width so far.*/
do m=1 for n; _=word(ILF,m); @.m=_; w=max(w,length(_)) /*store #s──►@.*/
end /*m*/ /**/
/* └─── is the maximum width of numbers*/
call radSort n /*invoke the radix sort subroutine. */
do j=1 for n; say 'item' right(j,w) "after the radix sort:" right(@.j,w); end
exit /*stick a fork in it, we're all done. */
/*───────────────────────────────────RADSORT subroutine───────────────────────*/
radSort: procedure expose @. w; parse arg size; mote=c2d(' '); #=1; !.#._n=size
/*REXX program performs a radix sort on an integer array (can be negative/zero/positive)*/
call gen /*call subroutine to generate numbers. */
call radSort n /*invoke the radix sort subroutine. */
/* [↓] display sorted items ───► term.*/
do j=1 for n; say 'item' right(j,w) "after the radix sort:" right(@.j,w); end
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
gen: w=0 /*the max width of an number in the ILF*/
ILF=' 0 2 3 4 5 5 7. 6 6 7 11 7 13 9 8 8 17 8 19 9 10 13 23 9 10 15' ,
' 9 11 29 10 31 10 14 19 12 10 37 21 16 11 41 12 43 15 11 25 47 11 14 12 20 17' ,
'53 11 16 13 22 31 59 12 61 33 13 12 18 16 67 21 26 14 71 12 73 39 13 23 18 18' ,
'79 13 12 43 83 14 22 45 32 17 89 13 20 27 34 49 24 13 97 16 17 14 101' ,
'22 103 19 15 55 107 13 109 18 40 15 113 -42'
/*excluding -42, abbreviated above list is called the integer log function*/
n=words(ILF) /* I────── L── F───────*/
do m=1 for n; _=word(ILF,m)+0; @.m=_; w=max(w,length(_)); end
return /* [↑] W: max width of numbers. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
radSort: procedure expose @. w; parse arg size; mote=c2d(' '); #=1; !.#._n=size
!.#._b=1;
!.#._i=1; do i=1 for size; y=@.i; @.i=right(abs(y),w,0); if y<0 then @.i='-'@.i
end /*i*/ /* [↓] where the rubber meats the road*/
/*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/
do while #\==0; ctr.=0; L='ffff'x; low=!.#._b; n=!.#._n; $=!.#._i; H= /**/
#=#-1 /* [↑] is radix.*/ /**/
do j=low for n; parse var @.j =($) _ +1; ctr._=ctr._+1 /**/
if ctr._==1 & _\=='' then do; if _<<L then L=_; if _>>H then H=_ /**/
end /**/ /**/
end /*j*/ /* └── << is a strict comparison.*/ /**/
_= /* ┌── >> " " " " */ /**/
if L>>H then iterate /*◄─┘ */ /**/
if L==H & ctr._==0 then do; #=#+1; !.#._b=low; !.#._n=n; !.#._i=$+1; iterate /**/
end /**/
L=c2d(L); H=c2d(H); ?=ctr._+low; top._=?; ts=mote /**/
max=L /**/
do k=L to H; _=d2c(k,1); cen=ctr._ /**/
if cen>ts then parse value cen k with ts max /*swap.*/ /**/
?=?+cen; top._=? /**/
end /*k*/ /**/
piv=low /*set pivot to the low part.*/ /**/
do while piv<low+n /**/
it=@.piv /**/
do forever; parse var it =($) _ +1; cen=top._-1 /**/
if piv>=cen then leave; top._=cen; ?=@.cen; @.cen=it; it=? /**/
end /*forever*/ /**/
top._=piv /**/
@.piv=it; piv=piv+ctr._ /**/
end /*while piv<low+n */ /**/
i=max /**/
do until i==max; _=d2c(i,1); i=i+1; if i>H then i=L; d=ctr._ /**/
if d<=mote then do; if d>1 then call .radSortP top._,d; iterate; end /**/
#=#+1; !.#._b=top._; !.#._n=d; !.#._i=$+1 /**/
end /*until i==max */ /**/
end /*while #\==0 */ /**/
/*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/
#=0; do i=size by -1 to 1; if @.i>=0 then iterate; #=#+1; @@.#=@.i; end
do j=1 for size; if @.j>=0 then do; #=#+1; @@.#=@.j; end; @.j=@@.j+0; end
return /* [↑↑↑] combine 2 lists into 1 list. */
/*───────────────────────────────────.radSortP subroutine─────────────────────*/
.radSortP: parse arg bb,nn
do k=bb+1 for nn-1; q=@.k
do j=k-1 by -1 to bb while q<<@.j; jp=j+1; @.jp=@.j; end /*j*/
jp=j+1; @.jp=q
end /*k*/
return
!.#._i=1; do i=1 for size; y=@.i; @.i=right(abs(y), w, 0); if y<0 then @.i='-'@.i
end /*i*/ /* [↑] negative case*/
do while #\==0; ctr.=0; L='ffff'x; low=!.#._b; n=!.#._n; $=!.#._i; H=
#=#-1 /* [↑] is the radix. */
do j=low for n; parse var @.j =($) _ +1; ctr._=ctr._ + 1
if ctr._==1 & _\=='' then do; if _<<L then L=_; if _>>H then H=_
end /* ↑↑ */
end /*j*/ /* └┴─────◄─── << is a strict comparison.*/
_= /* ┌──◄─── >> " " " " */
if L>>H then iterate /*◄─────┘ */
if L==H & ctr._==0 then do; #=#+1; !.#._b=low; !.#._n=n; !.#._i=$ + 1; iterate
end
L=c2d(L); H=c2d(H); ?=ctr._ + low; top._=?; ts=mote
max=L
do k=L to H; _=d2c(k,1); c=ctr._ /* [↓] swap two item radices.*/
if c>ts then parse value c k with ts max; ?=?+c; top._=?
end /*k*/
piv=low /*set PIVot to the low part of the sort*/
do while piv < low+n
it=@.piv
do forever; parse var it =($) _ +1; c=top._ -1
if piv>=c then leave; top._=c; ?=@.c; @.c=it; it=?
end /*forever*/
top._=piv; @.piv=it; piv=piv + ctr._
end /*while piv<low+n */
i=max
do until i==max; _=d2c(i,1); i=i+1; if i>H then i=L; d=ctr._
if d<=mote then do; if d<2 then iterate; b=top._
do k=b+1 for d-1; q=@.k
do j=k-1 by -1 to b while q<<@.j; jp=j+1; @.jp=@.j; end
jp=j+1; @.jp=q
end /*k*/
iterate
end
#=#+1; !.#._b=top._; !.#._n=d; !.#._i=$+1
end /*until i==max*/
end /*while #\==0 */
#=0 /* [↓↓↓] handle neg. and pos. arrays. */
do i=size by -1 to 1; if @.i>=0 then iterate; #=#+1; @@.#=@.i; end
do j=1 for size; if @.j>=0 then do; #=#+1; @@.#=@.j; end; @.j=@@.j+0; end
return /* [↑↑↑] combine 2 lists into 1 list. */

View file

@ -1,18 +1,18 @@
class Array {
method radix_sort(base=10) {
var arr = self.clone;
var rounds = ([arr.minmax].map{.abs}.max -> log(base).floor + 1);
for i in ^rounds {
var buckets = (2*base -> of {[]});
var base_i = base**i;
var arr = self.clone
var rounds = ([arr.minmax].map{.abs}.max.ilog(base) + 1)
for i in (0..rounds) {
var buckets = (2*base -> of {[]})
var base_i = base**i
for n in arr {
var digit = (n/base_i % base);
digit += base if (0 <= n);
buckets[digit].append(n);
var digit = (n/base_i % base)
digit += base if (0 <= n)
buckets[digit].append(n)
}
arr = buckets.flatten;
arr = buckets.flat
}
return arr;
return arr
}
}
@ -22,5 +22,5 @@ for arr in [
[170, 45, 75, 90, 2, 24, -802, -66],
[100000, -10000, 400, 23, 10000],
] {
say arr.radix_sort;
say arr.radix_sort
}

View file

@ -0,0 +1,12 @@
fcn radixSort(ns){ // ints only, inplace, ns is mutable
b:=(0).pump(20,List,List().copy); // 20 [empty] buckets: -10..10
z:=ns.reduce(fcn(a,b){ a.abs().max(b.abs()) },0); // |max or min of input|
m:=1;
while(z){
ns.apply2('wrap(n){ b[(n/m)%10 +10].append(n) }); // sort on right digit
ns.clear(); b.pump(ns.extend); // slam buckets over src
b.apply("clear"); // reset buckets
m*=10; z/=10; // move sort digit left
}
ns
}

View file

@ -0,0 +1,2 @@
radixSort(T(170, 45, 75, 90, 802, 2, 24, 66)).println();
radixSort(T(170, 45, 75, -90, -802, 24, 2, 66)).println();