#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
typedef int ElemType;
typedef struct {ElemType *elem;int TableLen;
}SSTable;
void Init_ST(SSTable &ST,int len)//申请空间,并进行随机数生成
{ST.TableLen=len;ST.elem=(ElemType*) malloc(sizeof (ElemType)*ST.TableLen);srand(time(NULL));for (int i = 0; i < ST.TableLen; ++i) {ST.elem[i]=rand()%100;}
}
void Print_ST(SSTable ST)
{for (int i = 0; i < ST.TableLen; ++i) {printf("%3d",ST.elem[i]);}printf("\n");
}
void swap(ElemType &a,ElemType &b)
{ElemType temp;temp=a;a=b;b=temp;
}
void SelectSort(ElemType *A,int n)
{int i,j,min;//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(i!=min){swap(A[i],A[min]);}}
}
void AdjustDown(ElemType A[],int k,int len)
{int dad=k;int son=2*dad+1;//左孩子下标while (son<=len){if(son+1<=len && A[son]<A[son+1])//看下有没有右孩子,比较左右孩子选大的{son++;}if(A[son]>A[dad])//比较孩子和父亲,如果孩子大于父亲,那么进行交换{swap(A[son],A[dad]);dad=son;//孩子重新作为父亲,判断下一颗子树是否符合大根堆son=2*dad+1;} else{break;}}
}
void HeapSort(ElemType A[],int len)
{int i;//建立大根堆for(i=len/2;i>=0;i--){AdjustDown(A,i,len);}swap(A[0],A[len]);//交换顶部和数组最后一个元素//下面的策略就是,不但调整剩余元素为大根堆,因为根部最大,所以再次与A[i]交换(相当于放到数组后面),循环往复for(i=len-1;i>0;i--){AdjustDown(A,0,i);//剩下元素调整为大根堆swap(A[0],A[i]);}
}
int main() {SSTable ST;ST.TableLen=10;ST.elem=(ElemType*) malloc(sizeof (ElemType)*ST.TableLen);for (int i = 0; i < ST.TableLen; ++i) {scanf("%d",&ST.elem[i]);}SelectSort(ST.elem,10);Print_ST(ST);HeapSort(ST.elem,10);Print_ST(ST);return 0;
}
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#define N 10
typedef int ElemType;
void Merge(ElemType A[],int low,int mid,int high)
{static ElemType B[N];//加static的目的是无论多次递归,都只有一个B[N]int i,j,k;for(k=low;k<=high;k++)//复制元素到B中B[k]=A[k];//合并数组for(i=low,j=mid+1,k=i;i<=mid&&j<=high;k++){if(B[i]<=B[j])A[k]=B[i++];elseA[k]=B[j++];}while (i<=mid)//如果有剩余元素,接着放入即可A[k++]=B[i++];//前一半有剩余的放入while (j<=high)//如果有剩余元素,接着放入即可A[k++]=B[j++];//后一半有剩余的放入
}
void MergeSort(ElemType A[],int low,int high)//递归分割
{if(low<high){int mid=(low+high)/2;MergeSort(A,low,mid);//排序好前一半MergeSort(A,mid+1,high);//排序好后一半Merge(A,low,mid,high);//将连个排序好的数组合并}}
void print(int *a)
{for (int i = 0; i < N; ++i) {printf("%3d",a[i]);}printf("\n");
}
int main() {int A[10]={12,63,58,95,41,35,65,0,38,44};MergeSort(A,0,9);print(A);return 0;
}