Move all negative elements to end in ruby

Ruby program for Move all negative elements to end. Here more solutions.

#  Ruby program for
#  Move all negative elements at the end of array

#  Display array elements
def display(arr, n) 
	i = 0
	while (i < n) 
		print("  ", arr[i])
		i += 1
	end
	print("\n")
end

#  Swap the given array elements
def swap(arr, start, last) 
	temp = arr[start]
	arr[start] = arr[last]
	arr[last] = temp
end

#  Method which is move negative elements
def moveNegative(arr, n) 
	#  first index
	i = 0
	#  last index
	j = n - 1
	while (i < j) 
		if (arr[i] < 0 && arr[j] >= 0) 
			#  When [i] index are have negative value 
			#  And [j] is positive then swapping elements values
			swap(arr, i, j)
			#  Modified index
			i += 1
			j -= 1
		elsif(arr[i] >= 0) 
			#  When element of [i] is not negative
			i += 1
		else
			j -= 1
		end
	end
end

def main() 
	#  Array which are containing positive and negative values
	arr = [1, -1, 3, 2, -7, -5, 11, 6]
	n = arr.length
	print("Before Arrange : \n")
	#  Before move element
	display(arr, n)
	#  Move negative elements
	moveNegative(arr, n)
	#  After arrange
	print("After Arrange : \n")
	#  After move element
	display(arr, n)
end

main()

Output

Before Arrange : 
  1  -1  3  2  -7  -5  11  6
After Arrange : 
  1  6  3  2  11  -5  -7  -1



Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2022, kalkicode.com, All rights reserved