1.选择排序(时间复杂度O(n^2))
基本逻辑是:从0开始遍历选出最小值与0位交换,从1开始遍历再次选出最小值与1交换…,下面是代码,使用模板方法实现且增加了如何对自定以类进行排序
#include <iostream>
#include "Student.h"
using namespace std;
template<typename T>
void selectionSort(T arr[], int n){
for(int i = 0 ; i < n ; i ++){
int minIndex = i;
for( int j = i + 1 ; j < n ; j ++ )
if( arr[j] < arr[minIndex] )
minIndex = j;
swap( arr[i] , arr[minIndex] );
}
}
int main() {
// 测试模板函数,传入整型数组
int a[10] = {10,9,8,7,6,5,4,3,2,1};
selectionSort( a , 10 );
for( int i = 0 ; i < 10 ; i ++ )
cout<<a[i]<<" ";
cout<<endl;
// 测试模板函数,传入浮点数数组
float b[4] = {4.4,3.3,2.2,1.1};
selectionSort(b,4);
for( int i = 0 ; i < 4 ; i ++ )
cout<<b[i]<<" ";
cout<<endl;
// 测试模板函数,传入字符串数组
string c[4] = {"D","C","B","A"};
selectionSort(c,4);
for( int i = 0 ; i < 4 ; i ++ )
cout<<c[i]<<" ";
cout<<endl;
// 测试模板函数,传入自定义结构体Student数组
Student d[4] = { {"D",90} , {"C",100} , {"B",95} , {"A",95} };
selectionSort(d,4);
for( int i = 0 ; i < 4 ; i ++ )
cout<<d[i];
cout<<endl;
return 0;
}
"Student.h"//自定义类型
#include <iostream>
#include <string>
using namespace std;
struct Student{
string name;
int score;
bool operator<(const Student& otherStudent){
return score != otherStudent.score ?
score > otherStudent.score : name < otherStudent.name;
}
friend ostream& operator<<(ostream &os, const Student &student){
os<<"Student: "<<student.name<<" "<<student.score<<endl;
return os;
}
};
2.1插入排序(时间复杂度O(n^2))
基本逻辑是:从0到n依次取值,每次取值使得arr[i-1] < arr[i],代码实现如下:
template<typename T>
static void insertSort(T arr[],int size)
{
for(int i=1;i<size;i++)
{
for(int j=i;j>0;j--)
{
if(arr[j]<arr[j-1])
swap(arr[j],arr[j-1]);
else
break;
}
}
}
插入排序与选择排序的比较:选择排序对于第二层循环每次都要全部执行一遍,而插入排序可以提前退出,但这并不意味着插入排序的效率优于选择排序,因为选择排序的更多步骤是取值比较,交换操作很少,插入排序频繁的进行交换操作,交换操作更耗费时间。
2.2插入排序优化(实用)(时间复杂度O(n^2))
基本思想是在插入排序的基础上用赋值减少交换操作,代码实现如下:
template<typename T>
static void insertSortPlus(T arr[],int size)
{
for(int i=1;i<size;i++)
{
T num = arr[i];
int j;
for(j=i;j>0;j--)
{
if(num<arr[j-1])
{
//swap(arr[j],arr[j-1]);
arr[j] = arr[j-1];
}
else
{
break;
}
}
arr[j] = num;
}
}
在进入二层循环前保存arr[i],这样使得之前的交换数组元素操作(三次赋值)简化成了一次赋值,效率提高了接近三倍。而且在对本身就接近有序的数组排序时非常高效,比O(nlogn)时间复杂度的算法还要高效很多,因此O(n^2)算法在某些情况下是更好的选择。
3.冒泡排序(时间复杂度O(n^2))
冒泡排序和选择排序有些相似,但在实际应用中意义不大,基本思路是:从0到n遍历(n递减),如果arr[n]>arr[n+1],则交换数组元素。这样第k次循环后top k最大值放在了数组的倒数第k个位置。代码如下
template<class T>
static void bubbleSort(T arr[],int size)
{
for(int i=size;i>0;i--)
{
for(int j=1;j<i;j++)
{
if(arr[j-1]>arr[j])
swap(arr[j-1],arr[j]);
}
}
}
4.归并排序 (算法复杂度:O(nlogn))
https://blog.youkuaiyun.com/k_koris/article/details/80508543
5.快速排序(快速排序 双路快排 三路快排)
https://blog.youkuaiyun.com/k_koris/article/details/80585979
6.堆排序算法(时间复杂度O(N*logN),额外空间复杂度O(1),是一个不稳定性的排序)
https://guguoyu.blog.youkuaiyun.com/article/details/81283998