希尔排序:
// 最优情况下 时间复杂度为 o(n^1.3) ; 最差的情况下为 o(n^2) ,增量序列的最后一个增量值必须等于1
Shell_sort(vector<int> &v1){
int i, j , incre = v1.size() ;
do{
incre = incre/3+1 ;
for( i=incre+1; i<v1.size(); ++i){
if( v1[i]<v1[i-incre]){
v1[0] = v1[i] ;
for( j=i-incre; j>0&& v1[0]<v1[j]; j-=incre){
v1[j+incre] = v1[j] ;
}
v1[j+incre] = v1[0] ;
}
}
} while(incre>1);
}
堆排序:
void heapadjust(int a[], int m, int n)
{
int i, temp;
temp=a[m];
for(i=2*m;i<=n;i*=2)//从m的左孩子开始
{
if(i+1<=n && a[i]<a[i+1])//如果左孩子小于右孩子,则将i++,这样i的值就是最大孩子的下标值
{
i++;
}
if(a[i]<temp)//如果最大的孩子小于temp,则不做任何操作,退出循环;否则交换a[m]和a[i]的值,将最大值放到a[i]处
{
break;
}
a[m]=a[i];
m=i;
}
a[m]=temp;
}
void swap(int a[], int i, int j)
{
int temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
void heapsort(int a[], int n)
{
int i;
for(i=n/2; i>0; i--)//n/2为最后一个双亲节点,依次向前建立大顶堆
{
heapadjust(a, i, n);
}
for(i=n; i>1; i--)
{
swap(a, 1, i);//将第一个数,也就是从a[1]到a[i]中的最大的数,放到a[i]的位置
heapadjust(a, 1, i-1);//对剩下的a[1]到a[i-1],再次进行堆排序,选出最大的值,放到a[1]的位置
}
}
快速排序:
// 快排在枢纽选取时可以优化, 三数取中; 优化不需要的交换 , 交换直接变赋值; 优化小数组时的排序, high-low 小于一定个数时用直接插入排序
// 最好情况下 时间复杂度为o(n) 最坏 时间复杂度 o(n^2);
void swap(vector<int> & v1 , int index1, int index2){
int tmp = v1[index1];
v1[index1] = v1[index2] ;
v1[index2] = tmp ;
}
int sortCore(vector<int> &v1, int low, int high){
int threshold ;
threshold = v1[low] ;
while( low<high ){
while( low<high && threshold<=v1[high])
--high ;
swap(v1,low,high) ;
while( low<high && threshold>=v1[low])
++low;
swap(v1,low,high);
}
return low ;
}
void Qsort(vector<int> & v1,int low , int high){
int thresh_index ;
if( low<high ){
thresh_index = sortCore(v1,low,high) ;
Qsort(v1,low,thresh_index-1);
Qsort(v1,thresh_index+1,high) ;
}
}