以下是更新后的代碼:
def insertion_sort(list)
num = list.length
for i in (0..(num-2))
if list[i] > list[i 1] && i == 0
list[i], list[i 1] = list[i 1], list[i]
i =1
elsif list[i] == list[i 1]
i =1
elsif list[i] > list[i 1] && i > 0
len = (list[0..(i 1)].length)
list2 = list[0..(i 1)]
list = list - list2
count = 0
while count <= len 1
if list2[len-1] < list2[len-2]
list2[len-2],list2[len-1]= list2[len-1],list2[len-2]
elsif list2[len-1] == list2[len-2]
count =1
len-=len
else
count =1
len-=1
end
end
list = list2 list
end
end
list
end
p insertion_sort([2,1,4,8,7,3,100,99,8])
p insertion_sort([2,1,4,8,8,7,3,100,99])
p insertion_sort([3790,780,780,1,55])
概括:
- 如果兩個相同的整數彼此相鄰,則代碼有效:[2,1,4,8,8,7,3,100,99] 并且陣列大小 > 5。
- 如果兩個相同的整數在隨機位置:[2,1,4,8,7,3,100,99,8]。將發生以下錯誤 aaa.rb:4:in `>': Integer 與 nil 的比較失敗(ArgumentError)
第 4 行代碼為:if list[i] > list[i 1] && i == 0
解決1.我將while回圈更改為“while count <= len 1”,因此當陣列大小小于5時,代碼將起作用。但當相同的整數位于隨機位置時則不然。
有誰知道如何解決這個問題?提前致謝!
uj5u.com熱心網友回復:
感謝評論中的澄清。我現在看到了問題。
在交換演算法這里
elsif list[i] > list[i 1] && i > 0
len = (list[0..(i 1)].length)
list2 = list[0..(i 1)]
list = list - list2
count = 0
while count <= len 1
...
您正試圖將陣列一分為二。您得到list2陣列的前半部分,然后嘗試通過從 中減去 list2來得到后半部分list。
在這里使用減法的問題是,如果您有重復項,它將洗掉它們并使您的串列太短。
在這個例子中,[3790,1,780,55,23,50,1111,60,50]你應該50在第一個陣列中有 a 50,在后半部分有 a 。
但是使用減法會洗掉其中之一50。
當您將兩個臨時串列重新添加在一起時,您現在少了一個元素(缺少的50),并且當您到達陣列末尾并嘗試訪問不再存在的第 9 個元素時,您會收到越界錯誤。
在這里不使用減法,只需使用與 make 相同的方法即可list2。
list2 = list[0..(i 1)] # All elements in list from position 0 to i 1
list = list[(i 2)..-1] # All elements in list from position i 2 to end of list
現在list和list2只是原始串列拆分,當您將它們重新加在一起時,它們的長度應該相同
def insertion_sort(list)
num = list.length
for i in (0..(num-2))
if list[i] > list[i 1] && i == 0
list[i], list[i 1] = list[i 1], list[i]
i =1
elsif list[i] == list[i 1]
i =1
elsif list[i] > list[i 1] && i > 0
len = (list[0..(i 1)].length)
list2 = list[0..(i 1)]
list = list[(i 2)..-1]
count = 0
while count <= len 1
if list2[len-1] < list2[len-2]
list2[len-2],list2[len-1]= list2[len-1],list2[len-2]
elsif list2[len-1] == list2[len-2]
count =1
len-=len
else
count =1
len-=1
end
end
list = list2 list
end
end
list
end
p insertion_sort([2,1,4,8,7,3,100,99,8])
p insertion_sort([2,1,4,8,8,7,3,100,99])
p insertion_sort([3790,780,780,1,55])
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/359997.html
