不能调用`sort_exercise()`

时间:2018-03-13 20:49:22

标签: julia mergesort

我试图从sort_exercise

开始调用这两个函数
# 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)

1 个答案:

答案 0 :(得分:2)

您似乎已经翻译了Python代码。 事实上,在python L = [0] * (n1)中创建一个大小为n1的数组,填充为0.在Julia中,您可以使用L = zeros(Int, n1)来完成相同的操作。 L = zeros(Int, 1) * n1只是数组[0],因此您遇到了越界错误。

请注意,for i in range(1,n1)也可以写为for i = 1:n1