冒泡排序:
基本思想:在要排序的一组数中,对当前还未排好序的范围内的全部数,自上而下对相邻的两个数依次进行比较和调整,让较大的数往下沉,较小的往上冒。即:每当两相邻的数比较后发现它们的排序与排序要求相反时,就将它们互换。
#include <iostream>
using namespace std;
void swap(int &a,int &b)//交换元素
{
int temp=a;
a=b;
b=temp;
}
Bubble(int a[],int n)
{
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
swap(a[j],a[j+1]);
}
}
}
int main()
{
int a[]={3,5,2,7,-1,1,0,4,8,-6};
Bubble(a,10);
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}
Bubble(int a[],int n)
{
for(int i=0;i<n-1;i++)
{
bool exchange=true;//加入标志符,一旦一轮排序中没有发生元素交换,立即结束排序。
for(int j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
swap(a[j],a[j+1]);
exchange=false;
}
}
if(exchange)//结束排序
break;
}
}
改进二:
设置一标志性变量pos,用于记录每趟排序中最后一次进行交换的位置。由于pos位置之后的记录均已交换到位,故在进行下一趟排序时只要扫描到pos位置即可。
Bubble(int a[],int n)
{
int i=n-1;
while(i>0)
{
int pos=0;//每趟开始时无交换记录。
for(int j=0;j<i;j++)
if(a[j]>a[j+1])
{
swap(a[j],a[j+1]);
pos=j;//记录交换的位置
}
i=pos;//为下一趟排序准备
}
}
传统冒泡排序中每一趟排序操作只能找到一个最大值或最小值,我们考虑利用在每趟排序中进行正向和反向两遍冒泡的方法一次可以得到两个最终值(最大者和最小者) , 从而使排序趟数几乎减少了一半。
改进后的算法实现为:
基本思想:
1)选择一个基准元素,通常选择第一个元素或者最后一个元素,
2)通过一趟排序讲待排序的记录分割成独立的两部分,其中一部分记录的元素值均比基准元素值小。另一部分记录的 元素值比基准值大。
3)此时基准元素在其排好序后的正确位置
4)然后分别对这两部分记录用同样的方法继续进行排序,直到整个序列有序。
#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
int temp=a;
a=b;
b=temp;
}
int Sort(int a[],int low,int high)
{
int key=a[low];//基准元素
while(low<high)//从表的两端交替向中间扫描
{
while(low<high&&key<=a[high])high--;//从high 所指位置向前搜索,至多到low+1 位置。将比基准元素小的交换到低端
swap(a[low],a[high]);
while(low<high&&key>=a[low])low++;
swap(a[low],a[high]);
}
return low;
}
void Quick_Sort(int a[],int low,int high)
{
if(low<high)
{
int loc=Sort(a,low,high);//将表一分为二
Quick_Sort(a,0,loc-1);//递归对低表进行排序
Quick_Sort(a,loc+1,high);
}
}
int main()
{
int a[]={3,-7,2,7,-1,-8,9,4,5,-6};
Quick_Sort(a,0,9);
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}
快速排序是通常被认为在同数量级(O(nlog2n))的排序方法中平均性能最好的。但若初始序列按关键码有序或基本有序时,快排序反而蜕化为冒泡排序。为改进之,通常以“三者取中法”来选取基准记录,即将排序区间的两个端点与中点三个记录关键码居中的调整为支点记录。快速排序是一个不稳定的排序方法。
改进: 在本改进算法中 , 只对长度大于 k 的子序列递归调用快速排序 , 让原序列基本有序,然后再对整个基本有序序列用插入排序算法排序。实践证明,改进后的算法时间复杂度有所降低,且当 k 取值为 8 左右时 , 改进算法的性能最佳
#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
int temp=a;
a=b;
b=temp;
}
int Sort(int a[],int low,int high)
{
int key=a[low];//基准元素
while(low<high)//从表的两端交替向中间扫描
{
while(low<high&&key<=a[high])high--;//从high 所指位置向前搜索,至多到low+1 位置。将比基准元素小的交换到低端
swap(a[low],a[high]);
while(low<high&&key>=a[low])low++;
swap(a[low],a[high]);
}
return low;
}
void Q_Sort_improved(int a[],int low,int high,int k)
{
if(low<high-k)//长度大于k时递归
{
int loc=Sort(a,low,high);//将表一分为二
Q_Sort_improved(a,0,loc-1,k);//递归对低表进行排序
Q_Sort_improved(a,loc+1,high,k);
}
}
void Quick_Sort(int a[],int n,int k)
{
Q_Sort_improved(a,0,n,k);//先调用改进快排算法使之基本有序
for(int i=1;i<=n;i++)//再用插入排序对基本有序序列排序
{
int temp=a[i];
int j=i-1;
while(temp<a[j])
{
a[j+1]=a[j];
j--;
}
a[j+1]=temp;
}
}
int main()
{
int a[]={3,-7,2,7,-1,-8,9,4,5,-6};
Quick_Sort(a,9,4);
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}