- 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
- #该片段来自于http://www.codesnippet.cn/detail/080520133211.html
来源: http://www.codesnippet.cn/detail/080520133211.html