我有以下程序,它实现了一个排序包。它添加了元素 给出列表时成功按排序顺序(升序)。 当我使用另一个包的参数创建一个新的排序包时,它不是按排序顺序(而是按降序排列)。见下文
感谢您的帮助
# Array Class
#----------------------------------------------------
class Array(object): # Represents an array.
DEFAULT_CAPACITY = 5
def __init__ (self, capacity, fillValue = None):
'''Capacity = static size of array. fillValue is placed at each element'''
self._items = list()
self._capacity = capacity
self._logicalSize = 0
self._fillValue = fillValue
for count in range(capacity):
self._items.append(fillValue)
def __getitem__(self, index): return self._items[index]
def __setitem__(self, index, newItem):
self._items[index] = newItem
# ArraySortedBag Class
#----------------------------------------------------
class ArraySortedBag(object):
'''An array-based bag implementation'''
def __init__(self, sourceCollection = None):
'''Sets the initial state of self, which includes the contents
of sourceCollection, if it's present'''
self._items = Array(10)
self._size = 0
if sourceCollection:
for item in sourceCollection:
self.add(item)
def __len__(self): return self._size
def __iter__(self):
cursor = 0
while cursor < len(self):
yield self._items[cursor]
cursor += 1
def add(self, item):
'''Adds item to self.'''
insertIndex = 0
# First found the index where the item will be inserted at
for i in range(self._size):
if self._items[i] > item:
insertIndex = i
break
# Then, shift items down by one position until the insertIndex,
for i in range (self._size, insertIndex, -1):
self._items[i] = self._items[i-1]
# Last, assign value to _items[insertIndex]
self._items[insertIndex] = item
self._size += 1
# Test Driver
#----------------------------------------------------
if __name__ == "__main__":
b1 = ArraySortedBag([2000, 2, 1000])
print ("Display bag b1")
for i in b1: # <------ Correct order, ascending order
print (i)
b2 = ArraySortedBag(b1)
print ("\nDisplay bag b2")
for i in b2: # <----- Wrong order, descending order
print (i)
最佳答案
在 ArraySortedBag 类的第二个实例化中,您正在传递一个排序列表。 ArraySortedBag.init() 方法使用 add() 方法添加项目。当调用 add() 时,要添加的 item 永远不会小于现有列表。因此insertIndex保持等于0。因此,新项目将添加到列表的开头。
# First found the index where the item will be inserted at
for i in range(self._size):
if self._items[i] > item: # item is never less than self._items[i]
insertIndex = i
break
关于python - 按升序将元素添加到已排序的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29408661/