Any one can help me on this code


#this method sort the array that all 
#the even number in the first and the odd 
#number in the even, and reutnr #the number os swap, 
#e.g. in array = [17,4,8], there is a 17 odd number and 8 #even number. swaping so swapping them and the move is 1
function sort_even_odd(data)
	left = 1
	right = length(data)
	moves = 0
while left < right
	  	while iseven(data[left]) && left < right
	    	left += 1
	    end	  	
	    while isodd(data[right]) && left < right
	    	right -= 1
	    end 
	  	
	  	if left < right 
	    	data[left],data[right] = data[right],data[left]
	    	left += 1
	    	right -= 1
	    	moves += 1
	  	end 
	end
	#data, moves 
  moves
end 
data = [17 4 8];
println("Total  " , sort_even_odd(data))

FYI, it looks like you’re using quoting intended for speech rather than code. You want to use 3 backticks at the top and bottom of code blocks or press the button that looks like </>. Compare

function foo(speech)
println(“this doesn’t look good”)
end

to

function bar(code)
    println("ahh, much better")
end

You can still edit your post to fix it.

You should probably also say more about what your specific problem is, what else you’ve tried, etc. See this post for more information on how to write a question in a way that helps others to help you.

3 Likes

Without using fancy stuff, here is a simple implementation of the algorithm:

  1. Initialize two index variables left and right:
    left = 1, right = size
  2. Keep incrementing left index until we see an odd number.
  3. Keep decrementing right index until we see an even number.
  4. If left < right then swap data[left] and data[right]
function sort_even_odd(data)
	left = 1
	right = length(data)
	moves = 0

	while left < right		
	  	while iseven(data[left]) && left < right
	    	left += 1
	    end	  	
	    while isodd(data[right]) && left < right
	    	right -= 1
	    end 
	  	
	  	if left < right 
	    	data[left],data[right] = data[right],data[left]
	    	left += 1
	    	right -= 1
	    	moves += 1
	  	end 
	end
	data, moves 
end 

julia> data = [17 4 8];

julia> sort_even_odd(data)
([8 4 17], 1)
1 Like

thanks dear,
its working perfect.

i did not know that i can making the swap like this → data[left],data[right] = data[right],data[left]