I recently came across the programming language Julia, which is a very efficient language with a lot of tools that allow me to complete some tasks easily.
But I encountered a problem when learning how to use Julia to write a quick sort algorithm (using Hoare partition). In Wikipedia, Hoare partition is implemented using a do-while loop,which is not directly available in Julia, so I initially planned to use a basic while loop to avoid the do-while loop, and I had the following implementation:
begin
function quick_sort_hoare(
lst::Vector{N};
lb::Integer = 1,
ub::Integer = length(lst)
)::Vector{N} where { N }
copied_lst = copy(lst)
quick_sort_hoare!(copied_lst, lb, ub)
copied_lst
end
function quick_sort_hoare!(lst::Vector{N}, lb::Integer, ub::Integer) where { N }
if lb < 1 || ub < 1 || lb >= ub
nothing
else
pivot_index = hoare_partition!(lst, lb, ub)
quick_sort_hoare!(lst, lb, pivot_index)
quick_sort_hoare!(lst, pivot_index + 1, ub)
end
end
function hoare_partition!(
lst::Vector{N},
lb::Integer,
ub::Integer
)::Integer where { N }
pivot = lst[lb]
left_index = lb
right_index = ub
while true
while lst[left_index] < pivot
left_index = left_index + 1
end
while lst[right_index] > pivot
right_index = right_index - 1
end
if left_index >= right_index
break
end
lst[left_index], lst[right_index] = lst[right_index], lst[left_index]
end
right_index
end
end
But the algorithm implemented above is very slow and may not even work properly, so I adjusted the loop implementation, which is the following code:
begin
function quick_sort_hoare(
lst::Vector{N};
lb::Integer = 1,
ub::Integer = length(lst)
)::Vector{N} where { N }
copied_lst = copy(lst)
quick_sort_hoare!(copied_lst, lb, ub)
copied_lst
end
function quick_sort_hoare!(lst::Vector{N}, lb::Integer, ub::Integer) where { N }
if lb < 1 || ub < 1 || lb >= ub
nothing
else
pivot_index = hoare_partition!(lst, lb, ub)
quick_sort_hoare!(lst, lb, pivot_index)
quick_sort_hoare!(lst, pivot_index + 1, ub)
end
end
function hoare_partition!(
lst::Vector{N},
lb::Integer,
ub::Integer
)::Integer where { N }
pivot = lst[lb]
left_index = lb - 1
right_index = ub + 1
while true
while (left_index = left_index + 1; lst[left_index] < pivot) end
while (right_index = right_index - 1; lst[right_index] > pivot) end
if left_index >= right_index
break
end
lst[left_index], lst[right_index] = lst[right_index], lst[left_index]
end
right_index
end
end
The second implementation is correct, but I think the two implementations should be the same, so why is this?
Though the question may be very basic, I would appreciate guidance. Thank you in advance for your help.