及时终止的冒泡排序
/*
功能:交换两元素的数据
参数列表:
a---元素a
b---元素b
*/
template<class T>
void swap(T& a, T& b)
{
T temp;
temp = a;
a = b;
b = temp;
}
/*
功能:及时终止的冒泡排序,时间复杂度为n(n-1)/2
参数列表:
a[]---列表
n---列表元素个数
*/
template<class T>
void bubbleSort(T a[], int n)
{
bool is_sorted = true;
for (int i = n; is_sorted && i > 1; i--) //如果is_sorted一直没变,说明列表已经是排好序的,循环结束
{
is_sorted = false;//先设置为未交换,如果交换了就会被设置为交换。
for (int j = 0; j < i - 1; j++)
if (a[j] > a[j + 1])
{
swap<T>(a[j], a[j + 1]);
is_sorted = true;
}
}
}