The link for the error is above; I keep getting a noMethodError for a symbol and I am very confused
numList = [4,3,78,2,0,2]
def bubbleSort(list)
again = true
while again
copy = list
i = 0
until i == list.length do
list.each_with_index do |num, index|
if list[index+1] < num
tempNum = list[index+1]
list[index+1] = num
list[index] = tempNum
end
end
i = i+1
end
if copy != list
again = true
else
again = false
end
p copy
end
end
bubbleSort(numList)
As noted in comments, you are iterating with an index:
But this includes the last index, which you're trying to access one past.
list[index+1]returnnil, which will give the error you're seeing.It'd be important to avoid this access. I would also suggest avoiding the
againboolean flag. Rather useloopandbreakout of the loop at the appropriate time.Taking a step back and looking at how bubble sort works though, your implementation can be improved.
Each cycle through the array a bubble sort will advance the largest element to the end of the array. You don't need to cycle over the whole array each times, but can decrease the inner loop by one iteration each time.
You can also track the number of swaps. If no swaps are performed, the array is clearly sorted already, and the outer loop can be exited.
Three swaps are performed. The last position in the array is sorted.
One swap is performed. Now the last two positions are sorted.
One swap is performed. We know the last three positions are sorted. The first position therefore is sorted.
If the array is already sorted and we keep track of swaps:
Since zero swaps are performed, the array is known to be sorted. While bubble sort is worst case O(n^2), this technique can make it best case O(n).