我正在嘗試做陣列練習問題,我現在正在進行插入排序。我想知道這段代碼是否清晰可讀。對我來說,它看起來有點混亂,如果有人有更清晰的方式(更容易理解)來實現這一點,你可以幫我嗎?這是插入排序在紅寶石的正確實施
def insertion_sort(arr)
(1...arr.length).each do |i| #iterate through array go through every element
j=i-1 #to check all elements behind i
while(j>=0&&arr[i]<arr[j]) #while not out bounds and current element is less than previous
temp=arr[i] #3 lines to switch arr[i] and arr[j]
arr[i]=arr[j]
arr[j]=temp
i=j #keep track of where i is
j-=1 #decrease j by 1 to check the previous element
end
end
return arr
end
立即想到的是,你的縮進是可怕的,因此不容易閱讀。在stackoverflow上,Ruby的通用縮進規則是插入兩個空格。而且它很糟糕,因爲你沒有在二元關係/等號的周圍放置空格。 – sawa
此問題屬於[代碼評論](http://codereview.stackexchange.com/?as=1) –