0 Replies - 1259 Views - Last Post: 23 November 2009 - 01:22 PM

#1 erik.price   User is offline

  • D.I.C Lover
  • member icon

Reputation: 486
  • View blog
  • Posts: 2,690
  • Joined: 18-December 08

Bubblesort

Posted 23 November 2009 - 01:22 PM

Description: A relatively simple sorting algorithm. Any feedback is welcome, since I began learning Ruby yesterday and might not be following all the conventions
def bubbleSort(a)
  swapped = true
  while swapped == true
    i = 0
    swapped = false
    while(i < a.length-1):
      temp1 = a[i]
      temp2 = a[i+1]
      if (temp1 > temp2) then
        a[i], a[i+1] = temp2, temp1
        swapped = true
      end
      i += 1
    end
  end
  return a
end


#From here down is example usage of the function!

array = [1, 2, 6, 123, 32, -23, 2, -1, 2, 3, 123, 54]

puts "Before sorting:"
j = 0
while(j < array.length) #iterate through the loop, printing all values
  print array[j]
  print ' '
  j += 1
end
puts ""

bubbleSort(array)

puts "After sorting:"
k = 0
while(k < array.length)
  print array[k]
  print ' '
  k += 1
end


Is This A Good Question/Topic? 0
  • +

Page 1 of 1