Can someone help me out? I got a code for counting sort in Julia but it seems that it does not work. It gives me the wrong output. The code is down below:
NumEl - Number of elements MArray - Main Array minAr - Minimal value in the array maxAr - Maximum value in the array
NumEl = 30
MArray = Array{Int64}(undef, NumEl)
MArray .+= rand(1:100,length(MArray))
println("Our random array with $NumEl is: $MArray")
#Minimum and maximum element of the array
minAr = MArray[1]
maxAr = MArray[1]
println("--------------")
for i in 1:NumEl
if MArray[i] < minAr
global minAr = MArray[i]
elseif MArray[i] > maxAr
global maxAr = MArray[i]
end
end
println("Max element in the array: $maxAr\n")
println("Minimal element in the array: $minAr\n")
Size = maxAr - minAr + 1
Count = Array{Int64}(undef, Size + 1)
for i in 1:Size
Count[i] = 0
end
j = 0
for i in 1:10
Count[MArray[i] - minAr] = Count[MArray[i] - minAr ] + 1
end
z = 1
for i in minAr:maxAr
for j in 1:Count[i+1-minAr]
MArray[global z+=1] = i
end
end
println("--------------")
println("Our sorted array: $MArray")
There are 4 bugs I see, ignoring the global and style:
Lines 2:3 Adding a random value to an uninitiialized vector. Ouch, that can really throw the range of MArray off. Line 2 should be deleted and the results of
rand(1:100, NumEl)assigned directly toMArrayon line 3Line 31: 1:10 should be 1:NumEl
Line 32: indexes are off by 1
Line 35: z is off by 1
The rest is left to the OP to correct.