Search code examples
rubybubble-sort

Creating a bubble sort method from scratch and run into a "<" noMethod error


Making a bubble sort method from scratch and continually run into a noMethod error citing the "<" sign as the culprit.

array = [2, 1]

def bubble_sort(arg)
    count = 0
    while count < arg.length 
        arg.each do |n|
            if arg[n] > arg[n + 1]
                arg[n], arg[n + 1] = arg[n + 1], arg[n]
            end
            count += 1
        end
    end
    puts arg
end

bubble_sort(array)

Any help, beyond what I'm asking as well, will be much appreciated.


Solution

  • From first glance I can see a few problems with ur bubbles sort algo.

    editing ur code I came up with this... I do not have a means of running this as of now, so I don't know if the below code would also be valid... buh there's no harm in trying rai.

    count = 0
    
    while count < arg.length 
        n = 0
        while n < arg.length - count
            if arg[count] > arg[n+count]
                arg[count], arg[n+count] = arg[n+count], arg[count]
            end
            n += 1
        end
        count += 1
    end
    puts arg
    

    That should do the fix... lemme know if it doesn't work