Julia 无法调用'sort_exercise()`
我尝试调用这两个函数,从sort_练习开始Julia 无法调用'sort_exercise()`,julia,mergesort,Julia,Mergesort,我尝试调用这两个函数,从sort_练习开始 看起来您已经翻译了Python代码。 事实上,在python中,L=[0]*n1创建了一个大小为n1的数组,数组中填充了0。在Julia中,可以使用L=zerosInt,n1来完成相同的操作。 L=zerosInt,1*n1只是数组[0],因此存在越界错误 注意,对于范围1中的i,n1也可以写成i=1:n1。谢谢Alex!我已经做了改变,但还没有快乐。我真的很感谢你的帮助!Geeksforgeks是一个糟糕的参考。一个好的参考是 # reference
看起来您已经翻译了Python代码。 事实上,在python中,L=[0]*n1创建了一个大小为n1的数组,数组中填充了0。在Julia中,可以使用L=zerosInt,n1来完成相同的操作。 L=zerosInt,1*n1只是数组[0],因此存在越界错误
注意,对于范围1中的i,n1也可以写成i=1:n1。谢谢Alex!我已经做了改变,但还没有快乐。我真的很感谢你的帮助!Geeksforgeks是一个糟糕的参考。一个好的参考是
# reference https://www.geeksforgeeks.org/merge-sort/
# Merges two subarrays of A[]
# First subarray is A[p..m]
# Second subarray is A[m+1..r]
julia> function sort_exercise(A::Vector{Int}, p, m, r)
n1 = m - p + 1
n2 = r - m
# create temp arrays
L = zeros(Int, n1)
R = zeros(Int, n2)
# copy data to temp arrays L[] and R[]
for i = 1:n1
L[i] = A[p + i]
end
for j = 1:n2
R[j] = A[m + 1 + j]
end
# Merge temp arrays back to A[1..r]
i = 0 # Initial index of first subarray
j = 0 # Initial index of second subarray
k = p # Initial index of merged subarray
while i < n1; j < n2
if L[i] <= R[j]
A[k] = L[i]
i += 1
else
A[k] = R[j]
j += 1
end
k += 1
end
# Copy any possible remaining elements of L[]
while i < n1
A[k] = L[i]
i += 1
k += 1
end
# Copy any possible remaining elements of R[]
while j < n2
A[k] = R[j]
j += 1
k += 1
end
end
sort_exercise (generic function with 1 method)
julia> sort_exercise([4, 5, 22, 1, 3], 1, 3, 5)
ERROR: BoundsError: attempt to access 5-element Array{Int64,1} at index [6]
Stacktrace:
[1] sort_exercise(::Array{Int64,1}, ::Int64, ::Int64, ::Int64) at ./REPL[1]:14
julia> function merge_exercise(A::Vector{Int}, p, r)
if p < r
# equivalent to `(p + r) / 2` w/o overflow for big p and
h (no idea what h is)
m = (p+(r - 1)) / 2
# merge first half
merge_exercise(A, p, m)
# with second half
merge_exercise(A, m + 1, r)
# sort merged halves
sort_exercise(A, p, m, r)
end
end
merge_exercise (generic function with 1 method)