我一直在为双向链表实施冒泡排序:
def sort2(list) #bubble sort
for i in 0...list.length
for j in 0...list.length-1-i
if list.get(j+1)<list.get(j)
list.swap(j+1, j)
end
end
end
end
我不知道如何实现一个桶式排序。我们只能使用以下方法:
get(i)
- 返回值i
元素swap(i, j)
- 交换两个元素length(list)
- 返回列表长度这是get
,swap
和length
的代码:
def swap(i,j)
if i > j
i, j = j, i
elsif j == i
return
end
tmp = nil
list = @ListE.next #first element
for it in 0...j
if i == it
tmp = list
end
list = list.next
end
tmp.v, list.v = list.v, tmp.v
end
def get(i)
a = @ListE
while i>0
a = a.next
i-=1
end
return a.next.v
end
def length()
list = @ListE.next
length_of_list = 0
while list.v != nil
length_of_list += 1
list = list.next
end
return length_of_list
end
这是我尝试插入排序:
def sort3(list) #insertion sort
for i in 1...list.length
j = i
while j > 0 and list.get(j-1) > list.get(j)
list.swap(j-1, i)
j -= 1
end
end
end