一些简单的排序算法
冒泡排序,选择排序,插入排序,归并排序,快速排序,STL(sort ,推排序)
复杂度对比
算法分析
(以下图片均来自网络)
1、冒泡排序:
思路:两两比较,小数在前,大数在后,一次排序后,最大的数在最后,重 复n-2次,完成排序。
for(int i=1;i<=n-1;i++)
for(int j=i+1;j<=n-i+1;j++)
if(a[j-1]>a[j])
swap(a[j-1],a[j]);
2、 选择排序:
思路:每次找出未排序序列中最小的数排在前面。
for(int i=1;i<n;i++)
{
int minn;
for(int j=i+1;j<=n;j++)
if(a[j]<a[i])
minn=j;
swap(a[i],a[j]);
}
3、 插入排序:
思路:认定数组中第一个数字有序,将剩余n-1个数依次插入有序数列中
for(int i= 2; i<=n; i++)
{
if(a[i] < a[i-1])
{
int j= i-1;
int x = a[i];
while(j>0 && x < a[j])
{
a[j+1] = a[j];
j--;
}
a[j+1] = x;
}
}
4、 归并排序:
思路:分治思想,不断二分成最小单位,不断排序合并
void gb(int lo,int mid,int hi)
{
int i=lo;
int j=mid+1;
int x=0;
while(i<=mid&&j<=hi)
{
if(a[i]>a[j])
temp[x++]=a[j++];
else
temp[x++]=a[i++];
}
while(i<=mid)
temp[x++]=a[i++];
while(j<=hi)
temp[x++]=a[j++];
for(int i=0;i<x;i++)
a[lo+i]=temp[i];
}
void ef(int lo,int hi)
{
if(a==NULL||lo>=hi)
return;
if(lo<hi)
{
int mid=(lo+hi)>>1;
ef(lo,mid);
ef(mid+1,hi);
gb(lo,mid,hi);
}
}
5、 快速排序:
思路:二分,大数在右,小数在左,不断进行二分比较,直到无法分为止
void sort(int left,int right)
{
int x=left;
int y=right;
int z=a[(left+right)/2];
while(x<=y)
{
while(a[x]<z) x++;
while(a[y]>z) y--;
if(x<=y)
{
swap(a[x],a[y]);
x++;
y--;
}
}
if(left<y) sort(left,y);
if(right>x) sort(x,right);
}
6、STL
(1)sort
思路:最常用的排序,利用强大的stl,常用与结构体排序
#include<algorithm>
sort(a+1,a+1+n);
(2)堆排序
思路:依然是用强大的stl实现,默认小根堆,变成负数就是大根堆
#include<queue>
priority_queue<int,vector<int>,greater<int> >Q;
int x;
for(int i=1;i<=n;i++)
{
cin>>x;
Q.push(x);
}
while(!Q.empty())
{
cout<<Q.top();
Q.pop();
}