C++模板实现冒泡排序

来源:互联网 发布:梦幻之星新星捏脸数据 编辑:程序博客网 时间:2024/05/22 20:34

冒泡排序的思想是从数组(链表)末尾开始,对相邻的两个数据进行比较,如果小数据在后面,则交换位置.直到进行到开头位置,则称为进行了一次冒泡.最小的数据被冒泡到了开头位置.然后将开头位置向后移动一个单位,依次进行冒泡,直到某次冒泡没有发生数据交换或者冒泡的循环完毕为止.

冒泡排序特点:
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 happenstemplate <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;}
0 0
原创粉丝点击