排序算法
直接插入排序
void InsertSort(ElemType A[],int n){
int i,j;
for(i=2;i<=n;i++){
if(A[i]<A[i-1])
A[0]=A[i];
for(j=i-1;A[0]<A[j];j--){
A[j+1]=A[j];
}
A[j+1]=A[0];
}
}
折半直接插入排序
viod SInsertSort(ElemType A[],int n){
int i,j,low,high,mid;
for(i=2;i<=n;i++){
A[0]=A[i];
low=1;
high=i-1;
while(low<=high){
mid=(low+high)/2
if(A[mid]>A[0]) high=mid-1;
else low=mid+1;
}
for(j=i-1;j>=high+1;j--){
A[j+1]=A[j];
}
A[j+1]=A[0];
}
}
希尔排序
void ShellSort(ElemType A[],int n){
int i,j,dk;
for(dk=n/2;dk>=1;dk=dk/2){
for(i=dk+1;i<=n;i++){
if(A[i]<A[i-dk])
A[0]=A[i];
for(j=i-dk;j>0&&A[0]<A[j];j-=dk){
A[j+dk]=A[j];
}
A[j+dk]=A[0];
}
}
}
冒泡排序
void BubbleSort(ElemType A[],int n){
boole flag;
int i,j
for(i=0;i<n-1;i--){
flag=flase;
for(j=n-1;j>i;j--){
if(A[j-1]>A[j])
Swap(A[j-1],A[j]);
flag=true;
}
if(flag==flase)
return;
}
}
快速排序
void QuickSort(ElemType A[],int low,int high){
while(low<high){
int pivotps=Partition(A,low,high);
QuickSort(A,low,pivotps-1);
QuickSort(A,pivotps-1,high);
}
}
int Pivotps(ElemType A[],int low,int high){
ElemType pivot=A[low];
while(low<high){
while(low<high&&A[high]>=pivot]) --high;
A[low]=A[high];
while(low<high&&A[low]<=pivot) ++low;
A[high]=A[low];
}
A[low]=pivot;
return low;
}
选择排序
void SelectSort(ElemType A[],int len){
int i,j,min;
for(i=0;i<n-1;i++){
min=i;
for(j=i+1;j<n;++j){
if(A[j]<A[min])
min=j;
}
if(min!=i)
Swap(A[min],A[i]);
}
}
建立大根堆
void BuildMaxHesp(ElemType A[],int len){
for(int i=n/2;i>0;i--){
AdjustHeap(A,i,len);
}
}
void AdjustHeap(ElemType A[],int k,int len){
A[0]=A[k];
for(int i=2k;i<len;i=2){
if(A[i]<A[i+1]) ++i;
if(A[0]>=A[i]) break;
else
A[k]=A[i];
k=i;
}
A[k]=A[0];
}
void HeapSort(ElemType A[],int len){
BuildMaxHesp(A,len);
for(int i=len;i>1;i--){
Sweap(A[1],A[i]);
AdjustHeap(A,1,len-1);
}
}
typedef struct BiTNode{
TElemtype data;
struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;
int Depth(BiTree T){
int m,n = 0;
if(T == NULL){
return 0; // 递归结束,树深0
}
else{
int m = Depth(T->lchild); // 递归计算左子树深度
int n = Depth(T->rchild); // 递归计算右子树深度
if(m > n){
return m+1;
}
else{
return n+1;
}
}
}

浙公网安备 33010602011771号