Sorting algorithms/Counting sort: Difference between revisions

Content added Content deleted
(Racket version)
Line 1,290: Line 1,290:
(define (counting-sort xs min max)
(define (counting-sort xs min max)
(define ns (make-vector (+ max (- min) 1) 0))
(define ns (make-vector (+ max (- min) 1) 0))
(for ([x xs]) (vector-set! ns x (+ (vector-ref ns x) 1)))
(for ([x xs])
(vector-set! ns (- x min) (+ (vector-ref ns (- x min)) 1)))
(define ys (vector-copy xs))
(define ys (vector-copy xs))
(for/fold ([i 0]) ([n ns] [x (in-naturals min)])
(for/fold ([i 0]) ([n ns] [x (in-naturals)])
(for ([j (in-range i (+ i n ))])
(for ([j (in-range i (+ i n ))])
(vector-set! ys j x))
(vector-set! ys j (+ x min)))
(+ i n))
(+ i n))
ys)
ys)


(counting-sort #(0 9 3 8 1 1 1 2 3 7 4) 0 10)
(counting-sort #(0 9 3 8 1 -1 1 2 3 7 4) -1 10)
</lang>
</lang>
Output:
Output:
<lang racket>
<lang racket>
'#(0 1 1 1 2 3 3 4 7 8 9)
'#(-1 0 1 1 2 3 3 4 7 8 9)
</lang>
</lang>