Implementing quick sort with Ruby

时间:2016-04-04 19:02:51

标签: ruby quicksort

I wrote code for quick sort. I am getting an error for my sorting method but I don't see where the problem is

def sort (numbers, first, last)
if first >= last
    return
end

if first < last 
    pivot = first
    j = first
    k = last

    while (j < k) 
        if(numbers[j] >= numbers[pivot])
            j +=1 
            if(numbers[k] < numbers[pivot]) 
                k -=1 
                if(j <= k) 
                    temp = numbers[j]
                    numbers[j] = numbers[k]
                    numbers[k] = temp
                end
            end
        end
    end
    puts "end loop"
    temp = numbers[pivot]
    numbers[pivot]= numbers[k]
    numbers[k] = temp
    sort(numbers,first,k-1)
    sort(numbers,k+1,last)
end
end

a = [89, 23, 12, 67, 45, 78, 24, 56, 87, 73, 37] 
first = 0

for i in 0...a.length
puts a[i]
end

last = a.length - 1
puts "Array Count is #{last}"

sort(a, 0, last)

for i in 0...a.length
puts a[i]
end

error : sort': undefined method+@' for nil:NilClass (NoMethodError) Can anyone tell me what is this error about

1 个答案:

答案 0 :(得分:0)

首先,您的代码正在我的计算机上运行(修复了与++运算符相关的错误)。运行文件的方式一定有问题。 其次,代码看起来并不像Ruby代码(就像ruby没有++运算符一样)。查看我的示例实现 - Quick Sort