-1

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

anjali rai
  • 185
  • 1
  • 1
  • 14
  • 2
    To start, replace `j++` with `j += 1` and `k--` with `k -= 1`. [why ruby doesn't have ++ operators](http://stackoverflow.com/questions/3660563/why-doesnt-ruby-support-i-or-i-increment-decrement-operators) – T J Apr 04 '16 at 19:09
  • I'd suspect that one of your sublists is empty as would happen when k is either 1 or the list length. – Octopus Apr 04 '16 at 19:09
  • 1
    Please give the full text of the error, including line numbers and backtrace. All I know from this is that somewhere you tried to add to a nil value. Also please try to provide a [mcve]. – Shelvacu Apr 04 '16 at 19:10
  • Please change `j++` and `k--` as @TJ notes, rerun the code and if you still have an error, edit your question to reflect the updated information. When you report an exception, please also indicate the line on which it occurred. If I were you, I'd delete the question, make the changes, then undelete. – Cary Swoveland Apr 04 '16 at 19:15
  • I replaced j++ with j +=1 and same with k but when i run it after "array Count is 10" it goes to hang state. I have to terminate the program by pressing Ctrl+C – anjali rai Apr 04 '16 at 19:34
  • That's happening because you are missing the code needed to stop the recursion (an `if` clause). – Cary Swoveland Apr 04 '16 at 19:40
  • if first = last then it will stop the recursion – anjali rai Apr 04 '16 at 19:42
  • yes I mean that, if it is not correct what else i can implement – anjali rai Apr 04 '16 at 19:45

1 Answers1

0

First of all, your code is working on my computer (with fixing few errors with ++ operators). There must be some problem with how you are running the file. Secondly the code doesn't really look like Ruby code (like ruby doesn't have ++ operator). Check out my sample implementation - Quick Sort

hspandher
  • 15,934
  • 2
  • 32
  • 45