C++学习笔记51:排序

时间:2020-12-15 07:52:08
//直接插入排序函数模板
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;
}
}