2012-06-19 93 views
1

我試圖使用氣泡排序方法對僅有三個數字的數組進行排序。我使用的代碼如下。在不使用排序方法的Ruby中對數組進行排序

def my_sort(list) 
    return list if list.size <= 1 

    swapped = false 

    while !swapped 
    swapped = false 

    0.upto(list.size-2) do |i| 
     if list[i] > list[i+1] 
     list[i], list[i+1] = list[i+1], list[i] 
     swapped = true 
     end 
    end 

    list 
    end 

my_sort([3,1,2]) 

以下是錯誤消息我不斷收到:不應該包括

Syntax error, unexpected $end, expecting keyword_end 

我只是想知道這到底?

+4

縮進的代碼正確,你會看到丟失的'end'的時候了。 – tokland

+0

可能的重複[你如何排序而不使用排序方法?](http://stackoverflow.com/questions/11057381/how-do-you-sort-without-using-the-sort-method) –

回答

5

你錯過了endswapped = true。最好徹底和準確地縮進代碼以避免這種問題:

def my_sort(list) 
    return list if list.size <= 1 

    swapped = false 
    while !swapped 
    swapped = false 
    0.upto(list.size-2) do |i| 
     if list[i] > list[i+1] 
     list[i], list[i+1] = list[i+1], list[i] 
     swapped = true 
     end 
    end 
    end 

    list 
end 
3

你錯過了一個end

if list[i] > list[i+1] 
    list[i], list[i+1] = list[i+1], list[i] 
    swapped = true 
    end # <-------------------------------------------------------- 

編輯: 由於對方的回答中提到,縮進代碼,使這些錯誤更加明顯。

1

您的代碼適用於特定數組。因爲循環正在查看下一個元素是否更高,請滑動。但是數組中的更多元素呢?這是所有情況下的遞歸解決方案。

def my_sort(list, new_array = nil) 

    return new_array if list.size <= 0 
    if new_array == nil 
    new_array = [] 
    end 
    min = list.min 
    new_array << min 
    list.delete(min) 

    my_sort(list, new_array) 

end 

puts my_sort([3, 1, 2, 20, 11, 14, 3, 6, 8, 5]) 
-1
#Using bubble sort algorithm in ruby 

a = [1,5,7,2,3,50,78,34,89] 

a.size.times.each do |t| 
i=0 
a.each do |b| 
    if b > a[i+1] 
    a[i],a[i+1] = a[i+1],a[i] 
    end 
    i+=1 if i < a.size-2 
end 
end 
print a 
#output: [1, 2, 3, 5, 7, 34, 50, 78, 89] 
+0

Code-只有答案是不鼓勵的,因爲他們沒有解釋他們如何解決問題。請更新您的答案,以解釋這個問題已經具有的其他已接受和已獲得解答的答案是如何改進的。此外,這個問題已經5年了,您的努力將會得到最近沒有答案的用戶的讚賞。請複習[我如何寫出一個好答案](https://stackoverflow.com/help/how-to-answer)。 – FluffyKitten