Bubble Sort

Suppose there is an array of length \(N\), then the bubble sort algorithm will make \(N+1\) passes over the full array. We point to the first, \(p_1\), and second, \(p_2\), positions. If \(p_1 > p_2\), then swap the elements. We iteratively perform the same function on the entire array.

We define a helper function, swap!, which will swap elements in position u and v in the array, ary. We use a Ref which is kind of like a pointer so we can act directly on the array.

swap!(ary::Ref, u, v) = ary[][u], ary[][v] = ary[][v], ary[][u]

And then we define the bubble sort algorithm in the function bubble_sort.

function bubble_sort!(ary)
    n = length(ary)
    for i in 1:n
        for j in 1:(n-i)
            ary[j] > ary[j+1] && swap!(Ref(ary), j, j+1)