21:
friend void split(extendedChain<T>& a, extendedChain<T>& b, extendedChain<T>& c) {
chainNode<T>* cNode = c.chain<T>::firstNode;
a.clear();
b.clear();
for (int i = 0; i != c.chain<T>::listSize; i++) {
if (i % 2 == 0) {
b.push_back(cNode->element);
cNode = cNode->next;
}
else {
a.push_back(cNode->element);
cNode = cNode->next;
}
}
}
22:
void chain<T>::split(chain<T>& a, chain<T>& b)
{
chainNode<T>* bNode = firstNode;
chainNode<T>* aNode = firstNode->next;
a.firstNode = aNode;
b.firstNode = bNode;
for (int i = 0; i != listSize / 2-1; i++) {
bNode->next = aNode->next;
bNode = bNode->next;
aNode->next = bNode->next;
aNode = aNode->next;
}
if (listSize % 2 != 0) {
bNode->next = aNode->next;
b.listSize = listSize / 2 + 1;
a.listSize = listSize / 2;
}
else {
b.listSize = listSize / 2;
a.listSize = listSize / 2;
}
listSize = 0;
firstNode = NULL;
}
23:
//顺时针旋转I个元素。
template<class T>
void extendedChain<T>::circularShift(int i)
{
lastNode->next = chain<T>::firstNode;
for (int j = 0; j != i - 1; j++) {
lastNode = lastNode->next;
}
chain<T>::firstNode=lastNode->next;
lastNode->next = NULL;
}
26:最坏情况的复杂度约为1/6n^3,最好情况下1/2n^2.
template<class T>
void chain<T>::insertSort()
{
for (int i = 1; i < listSize; i++) {
T t = get(i);
int j;
for (j = i - 1; j >= 0 && t < get(j); j--) {
set(j + 1,get(j));
}
set(j + 1, t);
}
}
27选择排序:
template<class T>
void chain<T>::selectionSort() {
bool sorted = false;
for (int size = listSize; !sorted && (size > 1); size--) {
int indexOfMax=0;
sorted = true;
for (int i = 1; i < size; i++) {
if (get(indexOfMax) <= get(i))
indexOfMax = i;
else
sorted = false;
T t = get(indexOfMax);
set(indexOfMax, get(size - 1));
set(size - 1, t);
}
}
}