I don't understand why (bubble-sort! (vector 2 1)) returns #(2 2) with my code.
(define (bubble-sort! v)
(define (helper c orig-v n)
(cond
((< n 0)
v)
((> c n)
(helper 0 v (- n 1)))
((>= (vector-ref orig-v c) (vector-ref orig-v (+ c 1)))
(begin
(vector-set! v (+ c 1) (vector-ref orig-v c))
(vector-set! v c (vector-ref orig-v (+ c 1)))
(helper (+ c 1) v n)))
(else
(helper (+ c 1) v n))))
(helper 0 v (- (vector-length v) 2)))
I've traced through my code myself but have not found the problem.
In your code v
and orig-v
are the same vector (if you pass a vector as parameter the vector is not copied: this is similar to “call-by-reference” as it is called in other languages).
So inside the function you work on the vector passed as parameter, and the two expressions:
(vector-set! v (+ c 1) (vector-ref orig-v c))
(vector-set! v c (vector-ref orig-v (+ c 1)))
are equivalent to:
(vector-set! orig-v (+ c 1) (vector-ref orig-v c))
(vector-set! orig-v c (vector-ref orig-v (+ c 1)))
so 2 is copied in the second element (which contains 1), and then 2 is copied back in the first element, and the final result is #(2,2).