简单的查找排序

1.冒泡排序
void sort(int a[],int n)
{
int i,j,t;
for(i=1;ifor(j=0;jif(a[j]>a[j+1])
{
t=a[j+1];
a[j+1]=a[j];
a[j]=t;
}
} //O(n^2)
2.直接插入排序
void bisort(int a[],int n)
{
int i,j,temp;
for(i=1;ifor(j=i-1,temp=a[i];j>=0;j--)
if(a[j]>temp)
{
a[j+1]=a[j];
a[j]=temp;
}
} //O(n^2)
3.折半查找插入排序
void bisort(int a[],int n)
{
int i,j,temp,mid;
int low,high;
for(i=1;i{
temp=a[i];
low=0; high=i-1;
while(low<=high)//查找插入点
{
mid=(low+high)/2;
if(temphigh=mid-1;
else
low=mid+1;
}
for(j=i;j>low;j--)//移位
a[j]=a[j-1];
a[j]=temp;
}
} //O(n^2)
4.希尔排序
void sort(int a[],int dk,int n)
{//dk取值1,3,5...最后必须为一
int i,j,t;//dk是增量,shell sort也是一种插入排序
for(i=dk;ifor(j=i-dk,t=a[i];j>=0;j-=dk)
if(a[j]>t)
{
a[j+dk]=a[j];
a[j]=t;
}
}
void shellsort(int a[],int t,int n)
{
while(t>=1)
{ sort(a,t,n);
t=t-2;
}
}//O(nlog2n)
5.快速排序
int partition(int a[],int low,int high)
{
int piv;
piv=a[low];
while(low{
while(low=piv) high--;
a[low]=a[high];
while(lowa[high]=a[low];
}
a[low]=piv;
return low;
}
void Qsort(int a[],int low,int high)
{//采用递归实现快速排序
int piv;
if(low{
piv=partition(a,low,high);//对表进行分割
Qsort(a,low,piv-1);//对低子表递归排序,piv是枢轴位置
Qsort(a,piv+1,high);//对高子表递归排序
}
}//O(nlogn)
6.简单的选择排序
void sort(int a[],int n)
{
int i,j,temp;
for(i=0;ifor(j=i+1,temp=a[i];jif(temp>a[j])
{ a[i]=a[j];
a[j]=temp; temp=a[i]; }
}//O(n^2)
7.堆排序
void heapadjust(int *a,int i,int length)
{
int t,temp;
for(temp=a[i],t=2*i+1;t{
if(tif(temp>=a[t]) break;
a[i]=a[t];
a[t]=temp; i=t;
}
}
void heapsort(int *a,int length)
{
int i,temp;
for(i=length/2-1;i>=0;i--)//把无序序列按大顶堆排序
heapadjust(a,i,length);
for(i=length-1;i>0;i--)
{//按非递减排序
temp=a[0]; a[0]=a[i]; a[i]=temp;
heapadjust(a,0,i);
}
}//O(nlogn)

1.一般查找
int search(table st,int key)
{
int i;
st.a[0]=key;
for(i=st.length;key!=st.a[i];i--);
return i;
}//平均查找长度为3*(n+1)/4
2.折半查找---需有序时才可
int search(int a[],int n,int key)
{
int mid,low,high;
low=0; high=n-1;
while(low{
mid=(low+high)/2;
if(a[mid]==key) return mid;
else if(a[mid]else high=mid-1;
}
return 0;
}//n>50时,平均查找长度为log2(n+1)-1

相关文档
最新文档