对集合进行排序和向集合添加元素通常是两个独立的功能。当然,可以以对元素进行排序的方式将元素添加到集合中……但这与简单地对元素数组进行排序是一项非常不同的任务。
如果您只是尝试实现一个简单的排序算法,那么一种易于编码的简单(但不是最优)算法就是“延迟替换排序”。伪代码 fpr 将算法按升序排序如下:
Begin DELAYEDSORT
For ITEM=1 to maximum number of items in list-1
LOWEST=ITEM
For N=ITEM+1 to maximum number of items in list
Is entry at position N lower than entry at position LOWEST?
If so, LOWEST=N
Next N
Is ITEM different from LOWEST
If so, swap entry at LOWEST with entry in ITEM
Next ITEM
End DELAYEDSORT
延迟替换排序算法易于理解且易于编码。它通常比冒泡排序更快(交换次数更少),但仍然具有糟糕的时间复杂度 O(n^2),因此不适合对非常大的数据集进行排序。
如果您真的想将项目添加到已排序的集合中,则可以将新项目添加到集合的末尾,并使用上述方法对其进行处理。如果您正在处理大于几百或几千个元素的数据集,那么效率会很差。
仍然具有 O(n^2) 时间复杂度但可以适应组合添加和排序的替代解决方案是“插入排序”,其伪代码如下所示:
// The values in A[i] are checked in-order, starting at the second one
for i ← 1 to i ← length(A)
{
// at the start of the iteration, A[0..i-1] are in sorted order
// this iteration will insert A[i] into that sorted order
// save A[i], the value that will be inserted into the array on this iteration
valueToInsert ← A[i]
// now mark position i as the hole; A[i]=A[holePos] is now empty
holePos ← i
// keep moving the hole down until the valueToInsert is larger than
// what's just below the hole or the hole has reached the beginning of the array
while holePos > 0 and valueToInsert < A[holePos - 1]
{ //value to insert doesn't belong where the hole currently is, so shift
A[holePos] ← A[holePos - 1] //shift the larger value up
holePos ← holePos - 1 //move the hole position down
}
// hole is in the right position, so put valueToInsert into the hole
A[holePos] ← valueToInsert
// A[0..i] are now in sorted order
}