Amazon Affiliate

Monday, 20 June 2016

Insertion Sort in ruby.

# Insertion Sort in ruby.

def insertion_sort(array)
for i in 1..array.length - 1
j = i
temp = array[i]
while ((j>0) and (array[j-1] > temp))
array[j] = array[j-1]
j -= 1
end
array[j] = temp
end
return array
end

array = [6,5,3,1,8,7,2,4]
insertion_sort array
print array

Friday, 27 May 2016

Swap two variables in ruby.

#Swapping two variables in ruby :

puts "Enter first variable :"
a = gets.to_i
puts "Enter second variable :"
b = gets.to_i

puts "the value of a is :#{a}"
puts "the value of b is :#{b}"

puts "After exchanging the value :"

# Ist method

a,b = b,a
puts "the value of a is :#{a}"
puts "the value of b is :#{b}"

#2nd method using temporary variable

c = a
a = b
b = c
puts "the value of a is :#{a}"
puts "the value of b is :#{b}"

#3rd method using arithmetic operation

a = a+b
b = a-b
a = a-b
puts "the value of a is :#{a}"
puts "the value of b is :#{b}"