冒泡排序的思想是从数组(链表)末尾开始,对相邻的两个数据进行比较,如果小数据在后面,则交换位置.直到进行到开头位置,则称为进行了一次冒泡.最小的数据被冒泡到了开头位置.然后将开头位置向后移动一个单位,依次进行冒泡,直到某次冒泡没有发生数据交换或者冒泡的循环完毕为止.
冒泡排序特点:
1.稳定.
2.时间复杂度O(n2).
3.空间复杂度O(n2).
4.不需要额外空间.
程序实现如下:
//Bubble sort
//1. Stable
//2. Time complecity, O(n2)
//3. Space complecity, O(n2)
//4. Terminate condition, during one time compare, no change happens
template <typename T>
void Sort<T>::bubbleSort(T* const sortArray, const unsigned int size)
{
bool hasSwap = false;
for (unsigned int i = 0; i < size; i++)
{
hasSwap = false;
for (unsigned int j = size-1; j > i; j--)
{
loopTimes++;
if (sortArray[j] < sortArray[j-1])
{
T temp = sortArray[j];
sortArray[j] = sortArray[j - 1];
sortArray[j - 1] = temp;
hasSwap = true;
moveTimes++;
}
}
if (!hasSwap)
break;
}
return;
}