C++学习笔记51:排序

//直接插入排序函数模板
template <class T> void insertionSort(T a[], int n)
{
int i, ;
T temp; for (int i = ; i < n; i++)
{
int j = i;
T temp = a[i];
while (j > && temp < a[j-])
{
a[j] = a[j - ];
j--;
}
a[j] = temp;
}
}
//简单选择排序函数模板
template <class T> void mySwap(T &x, T &y)
{
T temp = x;
x = y;
y = temp;
} template <class T> void selectionSort(T a[], int n)
{
for (int i = ; i < n - ; i++)
{
int leastIndex = i;
for (int j = i + ; j < n; j++)
{
if (a[j] < a[leastIndex])
{
leastIndex = j;
}
}
mySwap(a[i], a[leastIndex]);
}
} //冒泡排序
template <class T> void bubbleSort(T a[], int n)
{
int i = n - ;
while (i > )
{
int lastExchangeIndex = ;
for (int j = ; j < i; j++)
{
if (a[j + ] < a[j])
mySwap(a[j], a[j + ]);
lastExchangeIndex = j;
}
i = lastExchangeIndex;
}
}
上一篇:Codeforces Round #191 (Div. 2) B. Hungry Sequence(素数筛选法)


下一篇:状态模式(State Pattern)