排序算法默认按从小到大排序?
-
冒泡排序
思路:从首记录开始,相邻两数比较,逆序则交换,每次排序使最大的排在最后
实现:
void BubbleSort(int a[],int n)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
int t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
}
-
快速排序
int Partition(int a[],int low,int high)
{
int t=a[low];
while(low<high)
{
while(low<high&&a[high]>=t)
high--;
a[low]=a[high];
while(low<high&&a[low]<=t)
low++;
a[high]=a[low];
}
a[low]=t;
return low;
}
void QSort(int a[],int low,int high)
{
if(low<high)
{
int mid=Partition(a,low,high);
QSort(a,low,mid-1);//递归
QSort(a,mid+1,high);
}
}
平均复杂度:o(n*log n),最坏时间复杂度o(n²),平均空间复杂度o(log n),不稳定
-
直接插入排序
思路:首记录自身有序,从第二个到最后一个每次都将当前记录插入前有序表中使其有序。
实现:
void InsertSort(int a[],int n)
{
for(int i=1;i<n;i++)
{
if(a[i]<a[i-1])
{
int t=a[i];
int j;
for( j=i-1;t<a[j];j--)
a[j+1]=a[j];
a[j+1]=t;
}
}
}
时间复杂度:o(n²),空间复杂度o(1),稳定
-
折半插入排序
思路:折半查找第一个比待插入数小的元素,再直接插入
实现:
void BInsertSort(int a[],int n)
{
for(int i=1;i<n;i++)
{
int t=a[i];
int low=1,high=i-1;
while(low<=high)
{
int mid=(low+high)/2;
if(a[mid]<t)
low=mid+1;
else
high=mid-1;
}//最后是low=high+1;
int j;
for( j=i-1;j>=high+1;j--)
{
a[j+1]=a[j];
}
a[high+1]=t;
}
}
时间复杂度:o(n²),基本有序时不如直接插入排序
-
希尔排序
思路:设增量序列,对每个子序列直接插入
实现:
void shellsort(int a[],int n)
{
for(int dk=n/2;dk>0;dk/=2)//增量为dk
{
for(int i=dk;i<n;i++)
{
for(int j=i-dk;j>=0&&a[j]>a[j+dk];j-=dk)
{
int t=a[j];
a[j]=a[j+dk];
a[j+dk]=t;
}
}
}
}
算法简单易记忆,但不稳定
-
简单选择排序
思路:每一趟选择最小的交换到最前面。
实现:
void SSort(int a[],int n)
{
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(a[j]<a[i])
{
int t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
}
- 堆排序
堆的概念:
对{r1,r2,r3...}序列,小顶堆
大顶堆
算法暂时未掌握。